MATLAB: Reshaping 2D matrix into 3D – specific ordering

MATLABreshape 2d 3d matrix

Hi,
I'd like to ask for your help in the following problem:
I have an n by m 2D matrix which is formed by concatenating a number of k by m matrices, where k < n and n/k is a positive integer. I want to construct a three dimensional matrix that stores each k by m matrix in a different layer in the third dimension. For example:
a =
0.6443 0.1948 0.5949 0.7303 0.0377
0.3786 0.2259 0.2622 0.4886 0.8852
0.8116 0.1707 0.6028 0.5785 0.9133
0.5328 0.2277 0.7112 0.2373 0.7962
0.3507 0.4357 0.2217 0.4588 0.0987
0.9390 0.3111 0.1174 0.9631 0.2619
0.8759 0.9234 0.2967 0.5468 0.3354
0.5502 0.4302 0.3188 0.5211 0.6797
0.6225 0.1848 0.4242 0.2316 0.1366
0.5870 0.9049 0.5079 0.4889 0.7212
0.2077 0.9797 0.0855 0.6241 0.1068
0.3012 0.4389 0.2625 0.6791 0.6538
0.4709 0.1111 0.8010 0.3955 0.4942
0.2305 0.2581 0.0292 0.3674 0.7791
0.8443 0.4087 0.9289 0.9880 0.7150
I want b to be
b
b(:,:,1) =
0.6443 0.1948 0.5949 0.7303 0.0377
0.3786 0.2259 0.2622 0.4886 0.8852
0.8116 0.1707 0.6028 0.5785 0.9133
0.5328 0.2277 0.7112 0.2373 0.7962
0.3507 0.4357 0.2217 0.4588 0.0987
b(:,:,2) =
0.9390 0.3111 0.1174 0.9631 0.2619
0.8759 0.9234 0.2967 0.5468 0.3354
0.5502 0.4302 0.3188 0.5211 0.6797
0.6225 0.1848 0.4242 0.2316 0.1366
0.5870 0.9049 0.5079 0.4889 0.7212
b(:,:,3) =
0.2077 0.9797 0.0855 0.6241 0.1068
0.3012 0.4389 0.2625 0.6791 0.6538
0.4709 0.1111 0.8010 0.3955 0.4942
0.2305 0.2581 0.0292 0.3674 0.7791
0.8443 0.4087 0.9289 0.9880 0.7150
What's the most efficient way to do this (preferably without the need for a loop)? The function 'reshape' picks elements column-wise, so it is not a viable option in this case.
Thank you,
Paul

Best Answer

[r,c] = size(a);
nlay = 3;
out = permute(reshape(a',[c,r/nlay,nlay]),[2,1,3]);
Yes, MATLAB does 'think' along rows. Then, transpose and reshape. Then, you need to re-'transpose' again but you have a 3D array thus use permute (nD general 'transpose').
Related Question