cumsum

Cumulative sum of array elements.

Category: Language Fundamentals > Operators and Elementary Operations

Syntax

B = cumsum(A)

Running sum along the first non-singleton dimension.

B = cumsum(A, dim)

Running sum along dimension dim.

Description

Element k of cumsum(x) is sum(x(1:k)). It is the discrete counterpart of integration, and the inverse of diff up to the first value: cumsum(diff(x)) equals x(2:end) - x(1).

For a matrix the sums run down each column; use cumsum(A, 2) to run along rows. Integer types saturate at their limits, and logical input is converted to double.

Input arguments

A
Numeric or logical array.
dim
Dimension to accumulate along.

Output arguments

B
Array of the same size as A; element k is the sum of the first k elements.

Example

cumsum(1:5)
A = [1 2; 3 4];
cumsum(A)
cumsum(A, 2)
cumsum(int8([100 100]))
Output
ans = 1×5

     1     3     6    10    15
ans = 2×2

     1     2
     4     6
ans = 2×2

     1     3
     3     7
ans = 1×2 int8 row vector

   100   127

See also

cumprod sum diff movsum