我希望在我进行部分计算的情况下合并结构字段,以便稍后填充整个结构字段单元格。
根据索引将结果放入细胞中,如下所示:
for i=3:4;
results1.index{i}=i;
results1.sqr{i}=i*i;
end
for i=1;
results2.index{i}=i;
results2.sqr{i}=i*i;
end
分别给予:
results1 =
index: {[] [] [3] [4]}
sqr: {[] [] [9] [16]}
results2 =
index: {[1]}
sqr: {[1]}
有没有办法合并结果结构以获得
allresults.index={[1] [] [3] [4]}
allresults.sqr={[1] [] [9] [16]}
我可以避免重叠结果,因此在价值冲突的情况下(例如,没有单元格为空)没有冲突解决或覆盖就可以了。 请注意,在较大的数据集中,单元格不限于标量,但可能包含单元格或其他类型。
答案 0 :(得分:5)
您可以先编写一个小帮助函数来合并单元格:
function R = mergeCells(A,B)
R = {};
IA = ~cellfun('isempty',A);
IB = ~cellfun('isempty',B);
R(IA) = A(IA);
R(IB) = B(IB);
end
然后在循环中调用它来合并字段
for k = 1:numel(F),
f = F{k};
allresults.(f) = mergeCells(results1.(f), results2.(f));
end
答案 1 :(得分:2)
这是实现这一目标的功能。我认为这是相当普遍的,它确实处理字符串但确实没有冲突。如果struct
具有不同的字段名称或不同数量的字段,则会失败。我无法告诉你有关性能的信息,或者是否有更好的方法可以做到这一点。
function T = structCat(re1,re2)
F=fieldnames(re1);
for i=1:length(F) %// Do one field name at a time
t1=re1.(F{i}); %// These are the individual cell arrays we are combining
t2=re2.(F{i});
if length(t2)>length(t1)
%// This loop just makes t1 be the longest cell array, it's a bit messy though
t1a=t1;
t1=t2;
t2=t1a;
end
T.(F{i})=t1; %// Now we know t1 is longer, set the new array to t1 initially
for j=1:length(t2) %// Do each element of t2 individually
if ~exist(T.(F{i}){j},'var') %// see if there is an element of t2 to insert into T
T.(F{i}){j}=t2{j}; %// if there is, insert it!
end
end
end
end
用法是,例如,
for i=3:4;
re1.index{i}=i;
re1.index2{i}=i^2;
re1.strings{i}='dafsd';
re1.mat{i}=[i;2*i;3*i];
end
for i=1;
re2.index{i}=i;
re2.index2{i}=i^2;
re2.strings{i}='hmmm';
re2.mat{i}=[i;2*i;3*i].^2;
end
T=structCat(re1,re2)
导致
T =
index: {[1] [] [3] [4]}
index2: {[1] [] [9] [16]}
strings: {'hmmm' [] 'dafsd' 'dafsd'}
mat: {[3x1 double] [] [3x1 double] [3x1 double]}
您还应该查看this question和this entry in the Matlab File Exchange,但我认为它们的确略有不同。
答案 2 :(得分:1)
这两个答案都有效。因此,我采用了大卫的一步法,结合了Mohsen的简单性:
function C = structCat2(A,B)
F=fieldnames(A);
for k = 1:numel(F),
f = F{k};
IA = ~cellfun('isempty',A.(f));
IB = ~cellfun('isempty',B.(f));
C.(f)(IA) = A.(f)(IA);
C.(f)(IB) = B.(f)(IB);
end