Combine three matrices (every other column)

12 visualizaciones (últimos 30 días)
Kim
Kim el 13 de Ag. de 2019
Comentada: Kim el 16 de Ag. de 2019
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 comentarios
Jos (10584)
Jos (10584) el 13 de Ag. de 2019
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 el 13 de Ag. de 2019
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.

Iniciar sesión para comentar.

Respuesta aceptada

Jos (10584)
Jos (10584) el 13 de Ag. de 2019
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 comentario
Kim
Kim el 16 de Ag. de 2019
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.

Iniciar sesión para comentar.

Más respuestas (2)

Bruno Luong
Bruno Luong el 13 de Ag. de 2019
Editada: Bruno Luong el 13 de Ag. de 2019
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) el 13 de Ag. de 2019
Editada: Jos (10584) el 13 de Ag. de 2019
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)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by