How to add (combine) together two structures with the same fields?

10 views (last 30 days)
Benson Gou
Benson Gou on 11 Jun 2021
Commented: Stephen on 11 Jun 2021
Dear All,
I have two structures A and B with the same fields. How can I combine them together to form a new structure?
For example, A = struct('field1', array1, 'field2', array2); B = struct('field1', array3, 'field2', array4). A and B have the same fields 'field1' and 'field2'. I want to combine A and B together to obtain structure C = struct('field1', [array1; array3], 'field2', [array2; array4]). array1 and array3 have the same number of columns, and array2 and array4 have the same number of columns.
Thanks.
Benson
  2 Comments

Sign in to comment.

Accepted Answer

KSSV
KSSV on 11 Jun 2021
clc; clear ;
s1.name = 'Tom' ;
s1.sex = 'm';
s1.age = 25 ;
s2.name = 'Harry' ;
s2.sex = 'f';
s2.age = 26 ;
% Structure array
s = [s1 ; s2]
% Single structure
S = struct ;
aField = fields(s1);
for i = 1:3
S.(aField{i}) = {s1.(aField{i}) s2.(aField{i})} ;
end
S
  3 Comments
Stephen
Stephen on 11 Jun 2021
Note that the loop does not concatenate the field data as your qustion shows, but instead nests the field data within a 1x2 cell array.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!