concatenate structs in a loop

조회 수: 7 (최근 30일)
S
S 2011년 5월 6일
I have a 1x7 struct, each containing the same number of rows but differing number of columns. I want to concatenate each struct into a new matrix but was wondering if I can do this in a loop?
For example, A is a 1x7 struct containing data B. I essentially want to do:
cat(2,A(1,1).B, A(1,2).B, A(1,3).B, A(1,4).B, A(1,5).B, A(1,6).B, A(1,7).B)
but in a loop. Is this possible? Thanks in advance.
  댓글 수: 1
Oleg Komarov
Oleg Komarov 2011년 5월 6일
but why in a loop?

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

채택된 답변

Matt Fig
Matt Fig 2011년 5월 6일
A 1-by-n structure, where the data in each n has the same number of rows but different number of columns:
A(1,1).B = [5.5 4.5;5.5 4.5];
A(1,2).B = [6.3 4.3 3.3;6.3 4.3 3.3];
A(1,3).B = [7.1 2.1 3.1 4.1;7.1 2.1 3.1 4.1];
Here is one way to do it in a loop:
G = cell(1,length(A));
for ii = 1:length(A)
G{ii} = A(ii).B;
end
G = [G{:}];
Or, simply (as Walter also pointed out):
G2 = cat(2,A(:).B); % isequal(G,G2)==1

추가 답변 (1개)

Paulo Silva
Paulo Silva 2011년 5월 6일
for n=1:size(A,1)
s{n}=cat(2,A(n,1).B, A(n,2).B, A(n,3).B, A(n,4).B, A(n,5).B, A(n,6).B, A(n,7).B);
end
  댓글 수: 2
S
S 2011년 5월 6일
Hi Paulo, first of all, thank you for the reply.
I should have been a bit more clear. I'd like to have it so that matlab recognizes how many structs are there and fills in the A1, A2, A3 ... An in the concatenate function. So if I have struct 1x7, I'd like to have matlab execute cat(2,A1,A2,A3,A4,A5,A6,A7) but if I had a struct 1x5, do cat(2,A1,A2,A3,A4,A5), if struct 1x8, then cat(2,A1,A2,A3,A4,A5,A6,A7,A8). Is this possible? Thanks again for your help.
S
Walter Roberson
Walter Roberson 2011년 5월 6일
cat(2,A.B)

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by