My problem is regarding reshaping arrays in Matlab.
I am reading in Matlab the "diegm.MAT" file from Fortran. The size of this array is 12x3, and I need a 4x3x3.
I tried the reshape function but does not work.
This is the array that I am reading:
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
And this is the array that I need:
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
Here you can get the .MAT file that I transfer to Fortran.
There is probably a more efficient way to do it but this seemed to work.
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])
Result:
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 is column-major so you need to transpose first
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.