필터 지우기
필터 지우기

Concatenation of arrays of structure

조회 수: 30 (최근 30일)
pietro
pietro 2014년 11월 1일
댓글: Image Analyst 2014년 11월 1일
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
Image Analyst
Image Analyst 2014년 11월 1일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2014년 11월 1일
Try this:
% Construct sample data
s=struct('a',[]);
s(1).a=[1:5;6:10]
s(2).a=[10:10:50;60:10:100]
% Now concatenate:
t1 = s(1).a'
t2 = s(2).a'
output = [t1(:), t2(:)]'
In the command window:
t1 =
1 6
2 7
3 8
4 9
5 10
t2 =
10 60
20 70
30 80
40 90
50 100
output =
1 2 3 4 5 6 7 8 9 10
10 20 30 40 50 60 70 80 90 100
Note I didn't use the field name of "a" on a structure also called "a" - I think that's a very bad idea that will lead to confusion, so I named my structure "s".
  댓글 수: 2
pietro
pietro 2014년 11월 1일
thanks for your reply. How can I adapt it for a more general solution? My struct array is 500 elements long.
Image Analyst
Image Analyst 2014년 11월 1일
Use a for loop
% Construct sample data
s=struct('a',[]);
s(1).a=[1:5;6:10]
s(2).a=[10:10:50;60:10:100]
s(3).a=[20:10:60;70:10:110]
% Now concatenate
for k = 1 : length(s)
this_t = s(k).a'
output(k, :) = this_t(:)';
end
output

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Jan
Jan 2014년 11월 1일
편집: Jan 2014년 11월 1일
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
per isakson 2014년 11월 1일
편집: per isakson 2014년 11월 1일
I assume that &nbsp [10:50;60:100] &nbsp should be &nbsp [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
&nbsp
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
pietro
pietro 2014년 11월 1일
Why? I need it for printing the result in one xls file
per isakson
per isakson 2014년 11월 1일
편집: per isakson 2014년 11월 1일
Because the for-loop is
  • easier to construct
  • easier to read and understand in three weeks from now
  • and - I guess - executes faster

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by