Jecimi
Jecimi

Reputation: 4173

Reshape matrix from 3d to 2d keeping specific order

I would like to resize a matrix under the form let's say 4x3x5, to a 2d matrix of 20x3 but while preserving the order as illustrated below :

Original Matrix Reshaped Matrix

The function reshape() does not keep this particular order, how could I achieve this the simplest way possible ?

Upvotes: 1

Views: 625

Answers (1)

Divakar
Divakar

Reputation: 221724

Let's solve these problems of concatenating and cutting across the third dimension once and for all!

Part I (3D to 2D) : Concatenate along the columns and across the 3rd dim of a 3D array, A to form a 2D array -

reshape(permute(A,[1 3 2]),[],size(A,2))

Part II (2D to 3D) : Cut a 2D array B after every N rows to form 3D slices of a 3D array -

permute(reshape(B,N,size(B,1)/N,[]),[1 3 2])

Sample run -

Part I (3D to 2D)

>> A
A(:,:,1) =
     4     1     4     3
     8     4     6     4
     8     5     6     1
A(:,:,2) =
     9     4     4     1
     2     2     9     7
     1     5     9     3
A(:,:,3) =
     4     4     7     7
     5     9     6     6
     9     3     5     2
>> B = reshape(permute(A,[1 3 2]),[],size(A,2));
>> B
B =
     4     1     4     3
     8     4     6     4
     8     5     6     1
     9     4     4     1
     2     2     9     7
     1     5     9     3
     4     4     7     7
     5     9     6     6
     9     3     5     2

Part II (2D to 3D)

>> N = 3;
>> permute(reshape(B,N,size(B,1)/N,[]),[1 3 2])
ans(:,:,1) =
     4     1     4     3
     8     4     6     4
     8     5     6     1
ans(:,:,2) =
     9     4     4     1
     2     2     9     7
     1     5     9     3
ans(:,:,3) =
     4     4     7     7
     5     9     6     6
     9     3     5     2

Upvotes: 4

Related Questions