Vertically concatenate fields with same names from different structures
Show older comments
I am trying to combine several structures with identical fields into a single structure by vertically concatenating the fields of the same name. All of the fields are numeric 1 or 2d arrays, which should make it straightforward, but I am stumped.
I essentially have a system with many structures named sequentially: Data1, Data2, and Data3, etc. There are many fields, but for simplicity envision that there are only 3, i.e. Data1.x, Data1.y, Data1.z; Data2.x, Data2.y, Data2.z; Data3.x, Data3.y, Data3.z;
I would like to vertically concatenate Data1.x, Data2.x, and Data3.x, then vertically concatenate all the y and z fields saving them into a new structure. If my system were this small, I'd just type it out, but there are many structures and fields I'd like to merge. Is there a away generically merge structures that have parallel fields/formats so that I can just provide the structure names (Data1, Data2, and Data3) as inputs? I've seen postings for merging structures with unique fields together but not merging structures by merging fields within the structures.
This thread seemed like a reasonable place to start, but I don't see how it works to merge multiple structures with different names. I think it would need an external for loop: http://www.mathworks.com/matlabcentral/newsreader/view_thread/317927
Accepted Answer
More Answers (1)
Andrei Bobrov
on 30 May 2013
data1 = struct('x',{12 [34 56] [2 4; 6 7]},'y',{23 67 09});
data2 = struct('x',{9 [2 2 2 2 2;3 3 3 3 3] [2 4; 6 7;9 6]},'y',{[3 5] [4 7] []});
d = [];
for j1 = 1:2
d = cat(3,d, struct2cell(eval(sprintf('data%d',j1))));
end
out = cell2struct(d,fieldnames(data1),1);
Categories
Find more on Structures in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!