MATLAB: Are leading singleton dimensions not dropped when displaying size of multidimensional arrays

arraydimensionsdroppedleadingMATLABmatrixmultidimensionalsingletonsize;squeezetrailing

When displaying sizes of multidimensional arrays, the SIZE function retains the leading singleton dimensions, but drops the trailing singleton dimensions.
For example, consider the following multidimensional array:
for i=1:160
myArr(:,:,i) = ones(128);
end
size(myArr(:,:,1))
For the array 'myArr', the SIZE function returns
ans =
128 128
However the commands:
size(myArr(:,1,:))
size(myArr(1,:,:))
return
ans =
128 1 160
ans =
1 128 160
respectively.

Best Answer

This is the expected behavior of multidimensional arrays.
Leading singleton dimensions are not dropped because they cannot be added on the fly (without a call to the RESHAPE function) to maintain memory integrity. However, trailing singleton dimensions are dropped because leaving them out will not affect memory integrity.
If the leading singleton dimensions are not required, the SQUEEZE function can be used. Hence for the example considered, the commands:
size(squeeze(myArr(:,1,:)))
size(squeeze(myArr(1,:,:)))
yield the results:
ans =
128 160
ans =
128 160
respectively, without displaying the singleton dimensions.
For more information regarding the SQUEEZE function, enter the following at the MATLAB Command Prompt:
doc squeeze