简体   繁体   English

MATLAB-第三矩阵维的级联

[英]MATLAB - concatenation of 3rd matrix dimension

I have a 3D matrix of size KxNxZ. 我有一个大小为KxNxZ的3D矩阵。 I would like to concatenate the sub matrices in the 3rd dimension into a single 2D matrix of size K*ZxN, st they will be concatenated by rows. 我想将第3维的子矩阵连接成一个大小为K * ZxN的2D矩阵,然后将它们按行连接。 What's the best way to achieve this result? 实现此结果的最佳方法是什么?

Thanks! 谢谢!

Example: 例:

%generates input
M = cat(3,[(1:3)',(4:6)'],[(7:9)',(10:12)'],[(13:15)',(16:18)']);
DesiredOutput = [[(1:3)';(7:9)';(13:15)'],[(4:6)';(10:12)';(16:18)']];

Input matrix 输入矩阵

M(:,:,1) =
 1     4
 2     5
 3     6

M(:,:,2) =
 7    10
 8    11
 9    12

M(:,:,3) =
13    16
14    17
15    18

Desired output matrix: 所需的输出矩阵:

DesiredOutput =

 1     4
 2     5
 3     6
 7    10
 8    11
 9    12
13    16
14    17
15    18

Eskapp is on the right track. Eskapp步入正轨。 First use permute to swap the second and third dimensions so that you get a K x Z x N matrix. 首先使用permute来交换第二维和第三维,以便获得K x Z x N矩阵。 Once you do that, you can use reshape to unroll the matrix so that you take each 2D slice of size K x Z and transform this into a single one column with each column of the 2D slice becoming unrolled. 完成此操作后,您可以使用reshape来展开矩阵,以便获取尺寸为K x Z每个2D切片,并将其转换为单列,使2D切片的每一列都展开。 Thankfully, this is how MATLAB works when reshaping matrices so naturally this will take very little effort. 值得庆幸的是,这是MATLAB在重塑矩阵时的工作方式,因此自然而然地花费了很少的精力。 You'd then concatenate all of these columns together to make your matrix. 然后,将所有这些列连接在一起以构成矩阵。

You first use permute this way: 您首先以这种方式使用permute

Mp = permute(M, [1 3 2]);

This tells us that you want to swap the second and third dimension. 这告诉我们您想交换第二维和第三维。 Next, use reshape on this matrix so that you ensure that each column has K x Z elements where each column of a 2D slice is unrolled into a single column. 接下来,在此矩阵上使用重reshape ,以确保每个列都有K x Z元素,其中2D切片的每个列都展开为单个列。

DesiredOutput = reshape(Mp, [], size(M,2));

size(M,2) accesses the value of N in the original matrix. size(M,2)访问原始矩阵中的N值。 You thus want to make DesiredOutput have K*Z rows and N columns. 因此,您要使DesiredOutput具有K*Z行和N列。 Doing [] automatically infers how many rows we have for the output matrix to make things easy. []自动推断出输出矩阵让我们轻松完成的行数。

We thus get: 因此,我们得到:

>> DesiredOutput

DesiredOutput =

     1     4
     2     5
     3     6
     7    10
     8    11
     9    12
    13    16
    14    17
    15    18

We can combine everything into one statement as the following if you don't want to use a temporary variable. 如果您不想使用临时变量,我们可以将所有内容组合为一个语句,如下所示。

DesiredOutput = reshape(permute(M, [1 3 2]), [], size(M,2));

I primarily used a temporary variable to explain each step in the process. 我主要使用一个临时变量来解释过程中的每个步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM