Vertically concatenate fields with same names from different structures

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

 採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 5 月 29 日

0 投票

I do not see how to do it without eval
field={'x','y','z'}
for ii=1:numel(field)
d=[]
for k=1:3
eval(['d=[d;' sprintf('data%d.%s',k,field{ii}) ']'])
end
eval([sprintf('data.%s',field{ii}) '=d'])
end

1 件のコメント

Meghan
Meghan 2013 年 5 月 29 日
Yes, this works! Thank you. Since there are 50 field names in my actual dataset, I just scripted the field name part with:
field=fieldnames(data1);
And it worked really well. It seems like 'eval' is often the best tool for iterative variable names. Thanks for pointing that out.

サインインしてコメントする。

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2013 年 5 月 30 日

1 投票

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);

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

製品

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by