Why is sum(X, 1) the sum of the columns in MATLAB?

Gtker picture Gtker · Apr 16, 2010 · Viewed 25.8k times · Source
>> X = [0 1 2
        3 4 5]

>> sum(X, 1)

ans =

     3     5     7

sum(X, 1) should sum along the 1st dimension(row) as per the document says:

S = SUM(X,DIM) sums along the dimension DIM.

But why does it actually sums along the 2nd dimension(column)?

Answer

Jonas picture Jonas · Apr 16, 2010

In my opinion, it is perfectly consistent with everything else.

sum(A,dim) sums along the direction of dimension dim.

Rows are counted "down", so sum(A,1) sums "down". Columns are counted "to the right", so sum(A,2) sums "to the right".

Another way to look at this is that sum(A,dim) collapses dimension dim to 1 by taking the sum. Thus, a 4x3 array summed along dimension 1 collapses the first dimension, leading to a 1x3 array.