Adding dissimilar structures together (not overwriting similar field values)

4 ビュー (過去 30 日間)
Amy
Amy 2017 年 2 月 21 日
編集済み: Jan 2017 年 2 月 27 日
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 日
Note: a{xx} is smarter than char(a(xx)).

サインインしてコメントする。

採用された回答

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);
Jan
Jan 2017 年 2 月 27 日
@Amy: This was a typo. See [EDITED].

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by