Adding dissimilar structures together (not overwriting similar field values)

10 views (last 30 days)
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 Comments
Amy
Amy on 22 Feb 2017
Edited: Amy on 22 Feb 2017
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

Sign in to comment.

Accepted Answer

Jan
Jan on 22 Feb 2017
Edited: Jan on 27 Feb 2017
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 Comments
Amy
Amy on 24 Feb 2017
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);

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 24 Feb 2017
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

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!