matlab - 如何合并/交错 2 个矩阵? [英] matlab - how to merge/interlace 2 matrices?

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

问题描述

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

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?

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

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

推荐答案

您所需要的只是一点点串联和重塑.首先,沿维度 2 进行串联,然后进行转置和线性化 (AB(:)),从而得到一个向量,其前三个元素是 A 的第一行,然后是 A 的第一行B,然后是 A 的第二行,依此类推.最后剩下的就是调用 reshape 将所有内容重新放入数组中.

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,[])'; 

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

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天全站免登陆