MATLAB: Efficiently converting a 3d matrix to a 2d matrix

concatenateMATLABreshape

Hello,
I would like to convert a 3d matrix into a 2d matrix. I want the 3rd dimension to be concatenated along dimension 1 in the 2d matrix. In the code below, the variable 'desired' illustrates what I want to achieve, but I want to do it more efficiently than via a for a loop. I tried doing the same with reshape (see variable B) but can't get it to produce the output I desire.
A(:,:,1) = ones(2,2);
A(:,:,2) = 2*ones(2,2);
A(:,:,3) = 3*ones(2,2);
desired = [];
for n = 1:size(A,3)
desired = cat(1,desired,A(:,:,n));
end
B = reshape(A,[],size(A,2),1);
Any advice would be much appreciated. Thanks for reading.

Best Answer

You can permute the 2nd and 3rd dimension before doing the reshape:
>> C = permute(A,[1 3 2]);
>> C = reshape(C,[],size(A,2),1)