How can I concatenate or merge two structures?

조회 수: 774 (최근 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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2006b

Community Treasure Hunt

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

Start Hunting!

Translated by