How can I concatenate or merge two structures?

1.755 views (last 30 days)
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?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
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 Comment
Royi Avital
Royi Avital on 23 May 2020
Is there a way which is MATLAB Codeer friendly?

Sign in to comment.

More Answers (7)

Ba Mo
Ba Mo on 12 Nov 2019
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!
  7 Comments
Carrie HE
Carrie HE on 9 Sep 2021
Excellent. I used your code and achieved my goal. I merge two structures vertically (with same field names), using
mergestructs = @(x,y) cell2struct([struct2cell(x),struct2cell(y)],fieldnames(x),1);

Sign in to comment.


James
James on 23 Aug 2016
You can do this manually:
f = fieldnames(structA);
for i = 1:length(f)
structB.(f{i}) = structA.(f{i})
end
  4 Comments
David Walwark
David Walwark on 29 Sep 2019
I second Dan on this. Please edit the answer so other people don't waste their time.

Sign in to comment.


John Beaumont
John Beaumont on 12 Sep 2017
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 )

Jiwon Yeon
Jiwon Yeon on 25 Feb 2021
If the two structure have the same fields, you can use 'cat' function.
combined = cat(1,structure1,structure2);

Peter Collins
Peter Collins on 10 Sep 2021
I created the attached function to tackle the case when there are duplicate fieldnames in the structures. Perhaps this helps.
function [c] = appendStruct(a,b)
%APPENDSTRUCT Appends two structures ignoring duplicates
% Developed to append two structs while handling cases of non-unique
% fieldnames. The default keeps the last occurance of the duplicates in
% the appended structure.
ab = [struct2cell(a); struct2cell(b)];
abNames = [fieldnames(a); fieldnames(b)];
[~,iab] = unique(abNames,'last');
c = cell2struct(ab(iab),abNames(iab));
end

Salomon Muller
Salomon Muller on 21 Feb 2018
This is not a solution. Since to merge tables the number of rows need to be the same as well.
  1 Comment
Peter Perkins
Peter Perkins on 21 Feb 2018
The original question is somewhat ill posed - it might refer to either two scalar structs or two struct arrays. Those are two different things, used in different contexts.
Salomon, you are correct that if the two structs are scalars, each field might contain vectors with different lengths (or even more general things), and converting to a table won't work.
But if the two structs are scalars whose fields all contain the same height vectors, or if the two structs are arrays, and in each element each field contains a scalar value, then struct2table/table2struct will work.
In fact, in either of those cases, it might even be better to stop half-way, and just use the table. One of the benefits of tables over scalar structs and struct arrays for tabular data is that tables allow for straight-forward subscripting in both dimensions. An Nx1 struct array with M fields supports convenient subscripting for "rows", but a scalar struct with M fields each containing an Nx1 vector doesn't make subscripting rows for more than one field easy at all. And neither support arbitrary subscripting across multiple fields.

Sign in to comment.


Pablo Nanez
Pablo Nanez on 12 Nov 2021 at 17:22
I had a similar question, how to replace values from one structure to another one (some kind of merging between two structures), and the structure can have several levels e.g, main.level1.level2.object.
This is my take on how to merge a portion of a structure into a larger one,
e.g,
a.a = 1;
a.b = 2;
a.z.a = 1;
a.z.b = 2
a = struct with fields:
a: 1 b: 2 z: [1×1 struct]
x.a = -1;
x.b = -1;
loco.x = 'asd'
loco = struct with fields:
x: 'asd'
So, the idea is to iterate over the struct to be merged (in this case x) and replace that part of the structure in the target structure (in this case a) when there is no more levels to check. Also it must allow to merge fields that does not exist in the target structure (in this case loco).
result = mergeStructure(a,x)
result = struct with fields:
a: -1 b: -1 z: [1×1 struct]
notice that the field z was not affected (even when it contains the same field names itself). You can also use the same code for changing the subfield z
a.z = mergeStructure(a.z,x);
a
a = struct with fields:
a: 1 b: 2 z: [1×1 struct]
a.z
ans = struct with fields:
a: -1 b: -1
finally, you can also merge fields that are not existing in the target structure
result = mergeStructure(a,loco)
result = struct with fields:
a: 1 b: 2 z: [1×1 struct] x: 'asd'
Here is the function
function [resultStruct] = mergeStructure(mainStruct,struct2merge)
fields2merge = fields(struct2merge);
for ifieldsIn = fields2merge'
moreLevels = isstruct(struct2merge.(ifieldsIn{1}));
if moreLevels
[valueInStructLeveli] = mergeStructure(mainStruct.(ifieldsIn{1}),struct2merge.(ifieldsIn{1}));
mainStruct.(ifieldsIn{1}) = valueInStructLeveli;
else
mainStruct.(ifieldsIn{1}) = struct2merge.(ifieldsIn{1});
end
end
resultStruct = mainStruct;
end

Products


Release

R2006b

Community Treasure Hunt

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

Start Hunting!

Translated by