Concatenation of arrays of structure
Show older comments
Hi all
I have to concatenate the field of an array of structure. Here a simple example:
a=struct('a',[]);
a(1).a=[1:5;6:10];
a(2).a=[10:50;60:100]; [EDITED, should be:] [10:10:50; 60:10:100]
Results:
Concatenated_afield=[1,2,3,4,5,6,7,8,9,10;10,20,30,40,50,60,70,80,90,100]
Thank you
Best regards
1 Comment
Image Analyst
on 1 Nov 2014
You can't do that unless you change the step in (2) to be 10 instead of 1, or change (1) to be a 2-by-41 array like (2) is instead of a 2 by 5 array.
Accepted Answer
More Answers (2)
a = struct('a',[]);
a(1).a = [1:5; 6:10];
a(2).a = [10:10:50; 60:10:100];
v = cat(2, a.a);
r = reshape(permute(reshape(v, 2, 5, 2), [3,2,1]), [2, 10]);
per isakson
on 1 Nov 2014
Edited: per isakson
on 1 Nov 2014
I assume that   [10:50;60:100]   should be   [10:10:50;60:10:100]
a=struct('a',[]);
a(1).a=[1:5;6:10];
a(2).a=[10:10:50;60:10:100];
>> cat( 1, transpose( a(1).a(:) ), transpose( a(2).a(:) ) )
ans =
1 6 2 7 3 8 4 9 5 10
10 60 20 70 30 80 40 90 50 100
 
And another try
transpose(cell2mat(arrayfun(@(s)reshape(transpose(s.a),[],1),a,'uni',false)))
ans =
1 2 3 4 5 6 7 8 9 10
10 20 30 40 50 60 70 80 90 100
And a for-loop
M = nan( length(a), length(a(1).a(:)) );
for jj = 1 : length( a)
M( jj, : ) = [ a(jj).a(1,:), a(jj).a(2,:) ];
end
xlswrite( filespec, M )
8 Comments
per isakson
on 1 Nov 2014
"but the result is different"   In what way different?
pietro
on 1 Nov 2014
per isakson
on 1 Nov 2014
Edited: per isakson
on 1 Nov 2014
ok - I fixed it
pietro
on 1 Nov 2014
per isakson
on 1 Nov 2014
Edited: per isakson
on 1 Nov 2014
Now I think I got it right. It's a bit ridiculous to squeeze it into one line. A plain for-loop is probably better.
pietro
on 1 Nov 2014
per isakson
on 1 Nov 2014
Edited: per isakson
on 1 Nov 2014
Because the for-loop is
- easier to construct
- easier to read and understand in three weeks from now
- and - I guess - executes faster
Categories
Find more on Loops and Conditional Statements 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!