MATLAB Function Reference Previous page   Next Page
sum

Sum of array elements

Syntax

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.

B = sum(..., 'double') performs 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') performs 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.

Remarks

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

Examples

The magic square of order 3 is

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

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

Nondouble Data Type Support

This section describes the support of sum for data types other than double.

Data Type single

You can apply sum to an array of type single and MATLAB returns an answer of type single. For example,

Integer Data Types

When you apply sum to any of the following integer data types, MATLAB returns an answer of type double:

For example,

If you want MATLAB to perform additions on an integer data type in the same integer type as the input, use the syntax

See Also

accumarray, cumsum, diff, isfloat, prod


Previous page  subvolume superiorto Next page

© 1994-2005 The MathWorks, Inc.