# Combine three matrices (every other column)

45 views (last 30 days)
Kim on 13 Aug 2019
Commented: Kim on 16 Aug 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 CommentsShowHide 1 older comment
Bruno Luong on 13 Aug 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.

Jos (10584) on 13 Aug 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]
Kim on 16 Aug 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.

Bruno Luong on 13 Aug 2019
Edited: Bruno Luong on 13 Aug 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) on 13 Aug 2019
Edited: Jos (10584) on 13 Aug 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)