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

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 thedim argument.

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 software returns an answer of type single. For example,

sum(single([2 5 8]))

ans =

     15

class(ans)

ans =

single

Integer Data Types

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

For example,

sum(single([2 5 8]});
class(ans)

ans =

single

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

sum(int8([2 5 8], 'native');
class(ans)

ans =

int8

See Also

accumarray, cumsum, diff, isfloat, prod

  


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