我正在使用matlab处理我的项目,我需要组合两个这样的矩阵:
A和B是16*50矩阵
我的新矩阵C应如下:
C =
A(1,1) A(1,2) ... A(1,50)
B(1,1) B(1,2) ... B(1,50)
A(2,1) A(2,2) ... A(2,50)
B(2,1) B(2,2) ... B(2,50)
. . .
. . .
. . .
A(16,1) A(16,2) ... A(16,50)
B(16,2) B(16,2) ... B(16,50)
Run Code Online (Sandbox Code Playgroud)
我该怎么办呢.谢谢.谢谢.
小智 5
学习可视化数组元素在内存中的位置,以及 reshape、permute 等工具如何对这些元素进行操作。
首先,你能简单地将两个矩阵一个一个地组合在一起吗?[A;B] 当然就足够了。
如果你然后对结果使用 reshape 会发生什么?所以像这样的事情......
reshape([A;B],[16,2,50])
Run Code Online (Sandbox Code Playgroud)
接下来,如果应用 permute 会发生什么?
permute(reshape([A;B],[16,2,50]),[2 1 3])
Run Code Online (Sandbox Code Playgroud)
我们接近了吗?如果你对那个结果进行了重塑怎么办?(是的,您可能希望通过几个步骤完成所有这些工作以使其具有可读性。当您需要在下个月或明年进行调试时,可读代码非常重要。同样重要的是说明代码块功能的注释行。 )
% interleave the rows of matrices A and B to create C
C = reshape([A;B],[16,2,50])
C = permute(C,[2 1 3]);
C = reshape(C,[32,50]);
Run Code Online (Sandbox Code Playgroud)
关键是,学习使用 matlab 中的工具在内存中移动元素,并牢记目标。在你完成之前,不要忘记那些评论。易于阅读的代码是易于调试的代码。如果我建议的单行注释不适合您,请添加更多行。评论几乎是免费的!它们只花费你几秒钟的时间来编写,没有时间执行,但它们可以不可估量地改进你的代码。
你应该首先阅读@woodchips的答案:了解MATLAB如何将数组存储在内存中非常重要.
在任何情况下,我会去:
C = zeros(2,16,50);
C(1,:) = A(:);
C(2,:) = B(:);
C = reshape(C, 32, 50);
Run Code Online (Sandbox Code Playgroud)
要么
C = zeros(32,50);
C(1:2:end,:) = A;
C(2:2:end,:) = B;
Run Code Online (Sandbox Code Playgroud)
由于这些方法避免重新排序元素.