[英]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.