Skip to Main Content Skip to Search
Product Documentation

sum - Sum of array elements

Syntax

B = sum(A)
B = sum(A,dim)
B = sum(..., 'double')
B = sum(..., dim,'double')
B = sum(..., 'native')
B = sum(..., dim,'native')

Description

B = sum(A) returns sums along different dimensions of an array. If A is floating point, that is double or single, B is accumulated natively, that is in the same class as A, and B has the same class as A. If A is not floating point, B is accumulated in double and B has class double.

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. The dim input is an integer value from 1 to N, where N is the number of dimensions in A. Set dim to 1 to compute the sum of each column, 2 to sum rows, etc.

B = sum(..., 'double') and B = sum(..., dim,'double') perform additions in double-precision and return an answer of type double, even if A has data type single or an integer data type. This is the default for integer data types.

B = sum(..., 'native') and B = sum(..., dim,'native') perform additions in the native data type of A and return an answer of the same data type. This is the default for single and double.

If A = int8(1:20) then sum(A) accumulates in double and the result is double(210) while sum(A,'native') accumulates in int8, but overflows and saturates to int8(127).

Tips

sum(diag(A)) is the trace of A.

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 either by transposing or using the dim argument.

See Also

cumsum | diff | isfloat | prod

  


» Learn more
» Download free kit
» Get trial software

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS