0

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.

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

Trey
  • 15
  • 4
  • 5
    "I tried the reshape function but does not work." Yes, it does. What did you try to do with that function? Please post your code. `reshape` takes data column-wise. It looks like you need to transpose your data first. – Cris Luengo May 31 '18 at 16:15
  • 1
    How did you try it? – Ander Biguri May 31 '18 at 16:28

2 Answers2

0

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
user3716193
  • 476
  • 5
  • 21
  • The only thing that copies data in your code is the transpose, the `reshape`s are essentially free. But you can combine all three reshapes into a single one. A note about your transpose: [use `.'`, not `'`](https://stackoverflow.com/q/25150027/7328782)! – Cris Luengo Jun 01 '18 at 16:50
  • The solution works perfect, but why you create the variable "output" ? Once its created the variable InputAsSingleRow, it can be created Output2 . I just want to understant the purpose of this part of the code. – Trey Jun 04 '18 at 13:44
0

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
Dan
  • 45,079
  • 17
  • 88
  • 157