[英]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文件。
可能有一种更有效的方法来执行此操作,但这似乎可行。
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主要用于列,因此您需要先转置
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.