Search code examples
matlabmultidimensional-arraydimensionstrailing

Matlab trailing singleton dimension


I have the following code

o = ones(4,3,2)
c = cellfun(@squeeze,num2cell(o,[2 3]), 'UniformOutput', false)

which gives as expected the 4 cells, each containing 3x2 matrixes.

But if I reduce the last dimension of o to one, the behavior is totally not as expected:

o = ones(4,3,1)
c = cellfun(@squeeze,num2cell(o,[2 3]), 'UniformOutput', false)

The output is:

[1x3 double]
[1x3 double]
[1x3 double]
[1x3 double]

Whereas I would expect:

[3x1 double]
[3x1 double]
[3x1 double]
[3x1 double]

Any possiblity how to obtain the correct result?


Solution

  • When the dimension of o is 4 x 3 x 1, num2cell(o, [2 3]) gives a 1 x 3 vector. As stated in the documentation, squeeze has no effect on a 2D array, so it will remain a row or column vector:

    Two-dimensional arrays are unaffected by squeeze; if A is a row or column vector or a scalar (1-by-1) value, then B = A.

    size(squeeze(rand(1, 3)))
    %   1   3
    
    size(squeeze(rand(3, 1)))
    %   3   1
    

    As pointed out by @Luis, you could replace squeeze with permute to get the dimensions you'd expect.

    c = cellfun(@(x)permute(x, [2 3 1]), num2cell(o,[2 3]), 'UniformOutput', false)