Combine three matrices (every other column)

조회 수: 3 (최근 30일)
Kim
Kim 2019년 8월 13일
댓글: Kim 2019년 8월 16일
I have three matrices A, B and C which are for example
A=[A11 A12 A13; A21 A22 A23; A31 A32 A33] , B=[B11 B12 B13; B21 B22 B23; B31 B32 B33] and C=[C11 C12 C13; C21 C22 C23; C31 C32 C33]
I would like to combine these matrices so that every other column is from A, B and C. Hence the resulting matrixshould be:
[A11 B11 C11 A12 B12 C12 A13 B13 C13; A21 B21 C21 A22 B22 C22 A23 B23 C23; A31 B31 C31 A32 B32 C32 A33 B33 C33]
My matrices are not only 3x3 matrices but 26 x 100 matrices so the resulting matrix should be 78x100. If I use
D=reshape([A;B;C], size(A,1), []);
I get the right order but my matrix is 26x100. If I use
D=reshape([A;B;C], [], size(A,2));
I get the right size but the order of the elements is wrong.
Since I don't have a lot of experience with Matlab, could you please help me figure out how to solve my problem?
  댓글 수: 2
Jos (10584)
Jos (10584) 2019년 8월 13일
Your question is a little confusing. In matlab, a 26-by-100 matrix means an array with 26 rows and 100 columns. Do you mean 100-by-26 matrices which would result in a matrix with 78 columns?
Bruno Luong
Bruno Luong 2019년 8월 13일
Agree, desciption is confusing. The number of columns of the resulting should be 3 times larger, then when OP describes 26 x 100, it's a number of rows that is 3 times larger.

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

채택된 답변

Jos (10584)
Jos (10584) 2019년 8월 13일
Or, as a one-liner, using left-hand indexing:
% some test data
A = cumsum(ones(5,4),2), B = 10 * A, C = 10 * B
% left-hand indexing trick (NewMatrix should not exist)
NewMatrix(:, (1:3) + (1:3:3*size(A,2)).' - 1) = [A B C]
  댓글 수: 1
Kim
Kim 2019년 8월 16일
Many thanks for the help. It was a mistake on my part, the matrix must have the dimensions 26x300. With this solution I have in any case the right order and it works perfectly, so thanks again.

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

추가 답변 (2개)

Bruno Luong
Bruno Luong 2019년 8월 13일
편집: Bruno Luong 2019년 8월 13일
rfun = @(x) reshape(x,[1 size(x)]);
D = reshape([rfun(A);rfun(B);rfun(C)],[],size(A,2))
The second method looks shorter but it actually requires some memory movement, so less efficient
D = reshape(permute(cat(3,A,B,C),[3 1 2]),[],size(A,2))

Jos (10584)
Jos (10584) 2019년 8월 13일
편집: Jos (10584) 2019년 8월 13일
Assuming matrices A, B and C all have the same N-by-M size:
% some test data
A = cumsum(ones(5,4),2) ; B = 10 * A ; C = 10 * B ;
NewMatrix = [A B C]
% reorder columns using indexing, "simple" and very efficient
M = size(A,2)
ix = (1:M) + (1:M:3*M).' - 1
NewMatrix = NewMatrix(:, ix)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by