How can I concatenate or merge two structures?
Mostrar comentarios más antiguos
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?
Respuesta aceptada
Más respuestas (3)
Ba Mo
el 12 de Nov. de 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!
2 comentarios
KAE
el 16 de Feb. de 2023
How do I execute this if I have two structures named Struct1 and Struct2?
John Beaumont
el 12 de Sept. de 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 )
James
el 23 de Ag. de 2016
You can do this manually:
f = fieldnames(structA);
for i = 1:length(f)
structB.(f{i}) = structA.(f{i})
end
Categorías
Más información sobre Tables en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!