Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

matrix - matlab - how to merge/interlace 2 matrices?

How can I combine 2 matrices A, B into one so that the new matrix C = row 1 of A, followed by row 1 of B, then row 2 of A, row 2 of B, row 3 of A, row 3 of B, etc? Preferably without a for loop?

ex: A = [1 2 3; 4 5 6], B = [5 5 5; 8 8 8].
AB = [1 2 3; 5 5 5; 4 5 6; 8 8 8].

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All you need is a bit of catenation and reshaping. First, you catenate along dimension 2, then you transpose, and linearize (AB(:)), so that you get a vector whose first three elements are the first row of A, then the first row of B, then the second row of A, etc. All that's left in the end is calling reshape to put everything back into an array again.

nColumns = size(A,2);
AB = [A,B]'; 
AB = reshape(AB(:),nColumns,[])'; 

Alternatively, you can construct AB directly via indexing. In this case, A is allowed to have one more row than B. This is probably faster than the above.

[nRowsA,nCols] = size(A);
nRowsB = size(B,1);

AB = zeros(nRowsA+nRowsB,nCols);
AB(1:2:end,:) = A;
AB(2:2:end,:) = B;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...