将矩阵从3d重塑为2d,并保持特定顺序

问题描述:

我想将矩阵的大小调整为4x3x5,将其转换为20x3的2d矩阵,但同时保留如下所示的顺序:

I would like to resize a matrix under the form let's say 4x3x5, to a 2d matrix of 20x3 but while preserving the order as illustrated below :

函数reshape()不保持此特定顺序,我如何才能以最简单的方式实现这一目标?

The function reshape() does not keep this particular order, how could I achieve this the simplest way possible ?

让我们一劳永逸地解决这些连接和切割三维空间的问题!

Let's solve these problems of concatenating and cutting across the third dimension once and for all!

第一部分(3D到2D):沿着列并跨过3D数组的3rd暗淡,A形成2D数组-

Part I (3D to 2D) : Concatenate along the columns and across the 3rd dim of a 3D array, A to form a 2D array -

reshape(permute(A,[1 3 2]),[],size(A,2))

第二部分(从2D到3D):每隔N行切一个2D数组B以形成3D数组的3D切片-

Part II (2D to 3D) : Cut a 2D array B after every N rows to form 3D slices of a 3D array -

permute(reshape(B,N,size(B,1)/N,[]),[1 3 2])

样品运行-

第一部分(3D到2D)

>> A
A(:,:,1) =
     4     1     4     3
     8     4     6     4
     8     5     6     1
A(:,:,2) =
     9     4     4     1
     2     2     9     7
     1     5     9     3
A(:,:,3) =
     4     4     7     7
     5     9     6     6
     9     3     5     2
>> B = reshape(permute(A,[1 3 2]),[],size(A,2));
>> B
B =
     4     1     4     3
     8     4     6     4
     8     5     6     1
     9     4     4     1
     2     2     9     7
     1     5     9     3
     4     4     7     7
     5     9     6     6
     9     3     5     2

第二部分(2D到3D)

>> N = 3;
>> permute(reshape(B,N,size(B,1)/N,[]),[1 3 2])
ans(:,:,1) =
     4     1     4     3
     8     4     6     4
     8     5     6     1
ans(:,:,2) =
     9     4     4     1
     2     2     9     7
     1     5     9     3
ans(:,:,3) =
     4     4     7     7
     5     9     6     6
     9     3     5     2