Adding dissimilar structures together (not overwriting similar field values)

4 vues (au cours des 30 derniers jours)
Amy
Amy le 21 Fév 2017
Modifié(e) : Jan le 27 Fév 2017
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 commentaires
Amy
Amy le 22 Fév 2017
Modifié(e) : Amy le 22 Fév 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 le 22 Fév 2017
Note: a{xx} is smarter than char(a(xx)).

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 22 Fév 2017
Modifié(e) : Jan le 27 Fév 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 commentaires
Amy
Amy le 24 Fév 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);
Jan
Jan le 27 Fév 2017
@Amy: This was a typo. See [EDITED].

Connectez-vous pour commenter.

Plus de réponses (1)

Guillaume
Guillaume le 24 Fév 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

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by