arraysmatlab

Converting a 3D array to a 2D array in Matlab


Suppose I have a 4x2x2 array such that

val(:,:,1) =

    1.0000   18.2190
    1.0000   15.4650
   12.0223   76.2841
   64.1669  104.7139

val(:,:,2) =

    1.0000   18.2190
   18.2190   18.6414
   11.5436   74.6475
   74.7046  110.4268

I am trying to "flatten" this 3D array into a 2D array so that it looks something like this

val(:,1) = 

    1.0000   
    18.2190
    1.0000   
    15.4650
    12.0223   
    76.2841
    64.1669
    104.7139

Is there a shorthand method for doing this so I can avoid using for-loops?


Solution

  • You can use a combination of permute() to rearrange your dimensions and then reshape() towards the desired format:

    tmp = permute(val, [3, 2, 1]);
    tmp2 = reshape(tmp, [size(tmp, 1), size(tmp, 2) * size(tmp, 3)]).'
    
    tmp2 =
    
        1.0000    1.0000
       18.2190   18.2190
        1.0000   18.2190
       15.4650   18.6414
       12.0223   11.5436
       76.2841   74.6475
       64.1669   74.7046
      104.7139  110.4268
    

    Or as a one-liner:

    tmp2 = reshape(permute(val, [3, 2, 1]), [size(val, 3), size(tmp, 2) * size(val, 1)]).'