【问题标题】:Reshaping 2d to 3d array in Matlab在 Matlab 中将 2d 重塑为 3d 数组
【发布时间】:2018-05-31 16:08:20
【问题描述】:

我的问题是关于在 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

【问题讨论】:

  • "我尝试了重塑功能,但不起作用。"是的,它确实。您尝试使用该功能做什么?请发布您的代码。 reshape 按列获取数据。看来您需要先转置数据。
  • 你是怎么尝试的?

标签: arrays matlab permutation reshape


【解决方案1】:

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

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

【讨论】:

  • 在代码中复制数据的唯一方法是转置,reshapes 基本上是免费的。但是您可以将所有三个重塑组合成一个。关于转置的注释:use .', not '!
  • 解决方案完美,但为什么要创建变量“输出”?一旦创建了变量 InputAsSingleRow,就可以创建 Output2 了。我只是想了解这部分代码的用途。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-08-05
    • 2016-01-17
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 2019-09-12
    相关资源
    最近更新 更多