MATLAB Function Reference
sum

Sum of array elements

Syntax

• ```B = sum(A)
B = sum(A`,`dim)
```

Description

```B = sum(A) ``` returns sums along different dimensions of an array.

If `A` is a vector, `sum(A)` returns the sum of the elements.

If `A` is a matrix, `sum(A)` treats the columns of `A` as vectors, returning a row vector of the sums of each column.

If `A` is a multidimensional array, `sum(A)` treats the values along the first non-singleton dimension as vectors, returning an array of row vectors.

```B = sum(A,dim) ``` sums along the dimension of `A` specified by scalar `dim`.

Remarks

`sum(diag(X))` is the `trace` of `X`.

Examples

The magic square of order 3 is

• ```M = magic(3)
M =
8    1    6
3    5    7
4    9    2
```

This is called a magic square because the sums of the elements in each column are the same.

• ```sum(M) =
15    15    15
```

as are the sums of the elements in each row, obtained by transposing:

• ```sum(M') =
15    15    15
```

`cumsum`, `diff`, `prod`, `trace`