How can I concatenate or merge two structures?

431 ビュー (過去 30 日間)
MathWorks Support Team
MathWorks Support Team 2009 年 6 月 27 日
編集済み: MathWorks Support Team 2023 年 3 月 30 日
I would like to merge two structures into a new structure containing all the fields of the two original structures. How can I do this in MATLAB?

採用された回答

MathWorks Support Team
MathWorks Support Team 2023 年 3 月 28 日
編集済み: MathWorks Support Team 2023 年 3 月 30 日
There is no direct ability in MATLAB that can be used to concatenate structures.
The attached file "mergeStructs.m" shows a number of methods that can be used to merge structures in MATLAB.
There are also online submissions on the MATLAB Central User Community that you can use. One such submission is:
Note that MathWorks does not guarantee or warrant the use or content of these submissions. Any questions, issues, or complaints should be directed to the contributing author.
  1 件のコメント
Royi Avital
Royi Avital 2020 年 5 月 23 日
Is there a way which is MATLAB Codeer friendly?

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

その他の回答 (3 件)

Ba Mo
Ba Mo 2019 年 11 月 12 日
This works IF AND ONLY IF there are no common fields (duplicate fields) in the 2 structures.
mergestructs = @(x,y) cell2struct([struct2cell(x);struct2cell(y)],[fieldnames(x);fieldnames(y)]);
I don't see why nobody pointed this out. it's intuitive!
  2 件のコメント
Adam Danz
Adam Danz 2021 年 2 月 10 日
Nice one, Ba Mo.
(Answer edited to format the line of code)
KAE
KAE 2023 年 2 月 16 日
How do I execute this if I have two structures named Struct1 and Struct2?

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


James
James 2016 年 8 月 23 日
You can do this manually:
f = fieldnames(structA);
for i = 1:length(f)
structB.(f{i}) = structA.(f{i})
end

John Beaumont
John Beaumont 2017 年 9 月 12 日
Convert structures to tables, then merge tables, then convert resulting table back to a structure.
% Create 1st structure
aa_s.val1 = 1;
aa_s.val2 = 2;
% Create 2nd structure
bb_s.val3 = 3;
bb_s.val4 = 4;
% Convert structures to tables
aa_t = struct2table( aa_s );
bb_t = struct2table( bb_s );
% Concatonate tables
merge_t = [ aa_t ,bb_t ];
% Convert table to structure
merge_s = table2struct( merge_t )

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品


リリース

R2006b

Community Treasure Hunt

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

Start Hunting!

Translated by