Adding dissimilar structures together (not overwriting similar field values)

4 Ansichten (letzte 30 Tage)
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 Kommentare
Amy
Amy am 22 Feb. 2017
Bearbeitet: Amy am 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
Jan
Jan am 22 Feb. 2017
Note: a{xx} is smarter than char(a(xx)).

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 22 Feb. 2017
Bearbeitet: Jan am 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 Kommentare
Amy
Amy am 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);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Guillaume
Guillaume am 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

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by