4

I am transforming a 3d matrix into a 2d matrix. This is the shape transformation: [n x m x o] -> [n*o x m].

The elements of the matrices are row-related. Thus, it is required to have the same rows in the resulting matrix.

A = rand(2,2,3);

Doing this:

C = reshape(A, 2*3, 2);

is not keeping the rows in A.

So I do this:

B = zeros(size(A,1)*size(A,3),size(A,2));
first_indice = 1;
for i = 1:size(A,3)
    B(first_indice:size(A,1)*i,:)=A(:,:,i);
    first_indice = first_indice + size(A,1);
end

Is there a more efficient way maybe using reshape?

Thanks a lot!

rauldg
  • 401
  • 4
  • 17

1 Answers1

4

reshape combines the matrix elements starting from the first dimension. Thus, the solution would be to permute the dimensions prior to reshaping. In your case it should be as follows:

% A is the input matrix of dimensions (n x m x o).
B = ipermute(A, [1 3 2]);
C = reshape(B, n*o, m);
nojka_kruva
  • 1,454
  • 1
  • 10
  • 23
  • Using permute instead of ipermute works too, isn't? I don't really understand 3d permutations ... – rauldg Dec 28 '11 at 15:03
  • 1
    Great anwer, which would deserve more than just two upvotes in my opinion. – Wok Oct 19 '12 at 08:36