MATLAB: Place each dimension of matrix into a cell array

3d matrixcell array

Given a matrix with 3 non-singleton dimensions, how can I place each 2d matrix (along dimension 1) into an element of a cell array?
Concretely:
Given
A(:,:,1) = [1 2; 3 4] A(:,:,2) = [5 6; 7 8]
How do you construct a cell array B such that
B{1} = [1 2; 3 4] B{2} = [5 6; 7 8]
Thanks! (I can write a for loop, but that seems awfully inefficient)

Best Answer

B = squeeze(mat2cell(A,2,2,[1 1]))
This is probably quicker:
mat2cell(reshape(A,2,4),2,[2 2])
More generally:
A(:,:,1) = [1 2; 3 4;5 6;45 50];
A(:,:,2) = [7 8;9 10;11 12;13 14];
A(:,:,3) = [70 80;90 100;110 120;130 140];
S = size(A);
B = mat2cell(reshape(A,S(1),S(2)*S(3)),S(1),ones(1,S(3))*S(2))