Adding dissimilar structures together (not overwriting similar field values)

15 次查看(过去 30 天)
Hello!
I have a series of simulation results that I want to put together into 1 structure.
S=load('results1.mat')
S(2)=load('results2.mat')
and so on.
This works well, except for when the fieldnames are not completely the same.
Lets say that results1.mat contains 280 field names, results2.mat contains 283 field names, and that 279 fieldnames are completely the same.
I would like to have all the fieldnames in my structure S. If the separate results-file didn't contain the fieldname, I want the fieldvalue to be empty. And unlike examples elsewhere on the internet, in my case I do not want to overwrite fields, rather I want to have columns with fieldvalues for each simulation run.
How can I do this in an automated way?
Thank you very much in advance!
  2 个评论
Amy
Amy 2017-2-22
编辑:Amy 2017-2-22
I think I solved my problem:
function A=merge_dissimilar_struct(A,B)
a=fieldnames(A);
b=fieldnames(B);
if ~isequal(a,b);
%Adding struct B to struct A, dissimilar fieldnames.
%Create a cell of fieldnames that do not occur in A, but do occur in B.
%Add fieldnames b of struct B (empty) to struct A.
for xx=1:length(b)
if ~isfield(A,char(b(xx)))
A().(char(b(xx)))=[];
end
end
%Add fieldnames a of struct A (empty) to struct B.
for xx=1:length(a)
if ~isfield(B,char(a(xx)))
B().(char(a(xx)))=[];
end
end
end
B=orderfields(B,A);
n=size(A,2);
A(n+1)=B;
end

请先登录,再进行评论。

采纳的回答

Jan
Jan 2017-2-22
编辑:Jan 2017-2-27
Or simpler:
function A = AppendStruct(A, B)
fB = fieldnames(B);
nA = numel(A) + 1;
for ifB = 1:numel(fB)
field = fB{ifB}; % [EDITED, typo, () -> {}]
A(nA).(field) = B.(field);
end
Now the existing fields are reused and new fields are created automatically.
  2 个评论
Amy
Amy 2017-2-24
With your code I get an error:
C.A=ones(2,2);
C.B=ones(15,2);
D.A=zeros(2,5);
D.B=zeros(15,5);
EE=AppendStruct(C,D);
Argument to dynamic structure reference must evaluate to a valid field name.
Error in AppendStruct (line 6) A(nA).(field) = B.(field);

请先登录,再进行评论。

更多回答(1 个)

Guillaume
Guillaume 2017-2-24
Another variant of the function:
function A = merge_dissimilar_struct(A,B)
for fld = setdiff(fieldnames(A), fieldnames(B))'
A(end).(fld{1}) = []; %add mising fields to A
end
for fld = setdiff(fieldnames(B), fieldnames(A))'
B(end).(fld[1}) = []; %add mising fields to B
end
A = [A, B];
end

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by