Matlab-如何合并/隔行扫描2个矩阵? [英] matlab - how to merge/interlace 2 matrices?

查看:150
本文介绍了Matlab-如何合并/隔行扫描2个矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将2个矩阵A,B合并为一个矩阵,这样新矩阵C = A的第1行,然后是B的第1行,然后是A的第2行,B的第2行,A的第3行, B之3,等等?最好没有for循环?

例如: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].

解决方案

您所需要的只是一些分类和重塑.首先,沿着维度2进行连接,然后转置并线性化(AB(:)),以便获得一个向量,该向量的前三个元素是A的第一行,然后是B的第一行,然后是A的第二行等等.最后剩下的就是调用reshape将所有内容重新放回数组中.

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

或者,您可以直接通过索引构造AB.在这种情况下,允许A比B多排一行.这可能比上面的快.

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

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

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].

解决方案

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;

这篇关于Matlab-如何合并/隔行扫描2个矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆