What exactly is first non singleton dimension of a matrix?

Viewed 3456

Looking at this definition:

: sum (x, dim)

If dim is omitted, it defaults to the first non-singleton dimension.

I tried few commands:

>> sum([2,3,4])         % A matrix of size 1*3 
ans =  9                 
>> sum([2;3;4;])        % A matrix of size 3*1
ans =  9
>> sum([2,3,4;2,3,4;2,3,4;])  % A matrix of size 3*3
ans =
   6   9   12

While these results intuitively don't surprise me much, the result#3 seems to me going against this accepted answer about the definition of "first non-singleton dimension".

Just to assure that it is picking default dim as 1:

>> sum([2,3,4;2,3,4;2,3,4;], 1)         % does COLUMN-WISE SUMMATION
ans =

    6    9   12

>> sum([2,3,4;2,3,4;2,3,4;], 2)         % does ROW-WISE SUMMATION
ans =

   9
   9
   9

So the question is if the accepted answer is correct, shouldn't the summation happen row-wise by default (considering the matrix is 3*3, and the row dimension > 1)?

1 Answers

The matrices in Matlab have as dimensions (1=rows, 2=columns, 3=depth, ...). Hence, for a matrix

>> A = [2, 3, 4;
        2, 3, 4;
        2, 3, 4]

the summation along dimension 1 will be the summation of the row elements (going down). The summation along dimension 2 will be along the columns (going right), etc.

Now, it is also possible to define a matrix, that does not have rows, but has only columns and depth. Then, because the rows dimension will be zero the command sum(A) will sum along the columns.

>> A = zeros(0,3,3);
>> A(1,:,:) = [2, 3, 4; 2 3 4; 2 3 4]
>> sum(A)
ans(:,:,1) =
     6
ans(:,:,2) =
     9
ans(:,:,3) =
    12
Related