在 Matlab 中重塑 2d 到 3d 数组

Reshaping 2d to 3d array in Matlab

我的问题是关于在 Matlab 中重塑数组。

我正在 Matlab 中阅读来自 Fortran 的 "diegm.MAT" 文件。这个数组的大小是12x3,我需要一个4x3x3.

我尝试了重塑功能,但没有用。

这是我正在读取的数组:

 5     2     5
 2     1     2
 4     3     2
 5     3     3
 5     2     4
 4     2     3
 1     1     3
 4     5     1
 3     3     1
 2     1     4
 2     3     1
 4     2     4

这是我需要的数组:

val(:,:,1) =

 5     1     2
 2     2     5
 5     4     3
 2     3     3

val(:,:,2) =

 5     2     3
 2     3     4
 4     1     5
 4     1     1

val(:,:,3) =

 3     1     1
 3     4     4
 1     2     2
 2     3     4

在这里你可以得到我转换为 Fortran 的 .MAT 文件。

http://www.mediafire.com/file/yhcj18ampvy92t5/diegm.mat

可能有更有效的方法,但这似乎有效。

Input = [ 
 5 2 5;
 2 1 2;
 4 3 2;
 5 3 3;
 5 2 4;
 4 2 3;
 1 1 3;
 4 5 1;
 3 3 1;
 2 1 4;
 2 3 1;
 4 2 4
 ];

% Make input matrix into 1x36 vector to preserve ordering
InputAsSingleRow = reshape(Input', [], 1);
% Reshape into 4x9 matrix  
Output = reshape(InputAsSingleRow,[4,9]);
% Reshape into 4x3x3 matrix you wanted
Output2 = reshape(Output,[4,3,3])

结果:

Output2 =

ans(:,:,1) =

   5   1   2
   2   2   5
   5   4   3
   2   3   3

ans(:,:,2) =

   5   2   3
   2   3   4
   4   1   5
   4   1   1

ans(:,:,3) =

   3   1   1
   3   4   4
   1   2   2
   2   3   4

MATLAB是column-major所以你需要先转置

octave:2> reshape(val.',4,3,[])
ans =

ans(:,:,1) =

   5   1   2
   2   2   5
   5   4   3
   2   3   3

ans(:,:,2) =

   5   2   3
   2   3   4
   4   1   5
   4   1   1

ans(:,:,3) =

   3   1   1
   3   4   4
   1   2   2
   2   3   4