sum

Sum of the elements of an array, along a dimension or over everything.

Category: Language Fundamentals > Data Types

Syntax

S = sum(A)

Sums along the first dimension that is not of size 1: down the columns of a matrix, or along a vector.

S = sum(A, dim)

Sums along dimension dim.

S = sum(A, 'all')

Sums every element and returns a scalar.

Description

For a matrix, sum(A) returns a row vector with the sum of each column, and sum(A, 2) returns a column vector with the sum of each row. Logical values count as 0 and 1, so sum(x > 3) counts how many elements exceed 3.

Input arguments

A
Numeric or logical array.
dim
Positive integer: the dimension to sum along.

Output arguments

S
The sums. The summed dimension has size 1 in the result; an empty array sums to 0.

Example

Columns, rows and everything

A = [1 2 3; 4 5 6];
sum(A)
sum(A, 2)
sum(A, 'all')
sum([2 7 1 9] > 3)
Output
ans = 1×3

     5     7     9
ans = 2×1

     6
    15
ans = 21
ans = 2

See also

cumsum prod mean max