Syntax

Description example

B = cumsum(A ) returns
an array of the same size as the array A containing
the cumulative sum.

If A is a vector, then cumsum(A) returns
a vector containing the cumulative sum of the elements of A.

If A is a matrix, then cumsum(A) returns
a matrix containing the cumulative sums for each column of A .

If A is a multidimensional array,
then cumsum(A) acts along the first nonsingleton dimension .

example

B = cumsum(A ,dim ) returns
the cumulative sum of the elements along dimension dim .
For example, if A is a matrix, then cumsum(A,2) returns
the cumulative sum of each row.

Examples expand all

Find the cumulative sum of the integers from 1 to 5 .

A = [1:5];
B = cumsum(A) B =
1 3 6 10 15 B(2) is the sum of A(1) and A(2) ,
while B(5) is the sum of elements A(1) through A(5) .

Define a 3-by-3 matrix whose elements correspond to their
linear indices.

A = [1 4 7; 2 5 8; 3 6 9] A =
1 4 7
2 5 8
3 6 9 Find the cumulative sum of the columns of A .

B = cumsum(A) B =
1 4 7
3 9 15
6 15 24 B(5) is the sum of A(4) and A(5) ,
while B(9) is the sum of A(7) , A(8) ,
and A(9) .

Define a 2-by-3 matrix whose elements correspond to their
linear indices.

A = [1 3 5; 2 4 6] A =
1 3 5
2 4 6 Find the cumulative sum of the rows of A .

B = cumsum(A,2) B =
1 4 9
2 6 12
B(3) is the sum of A(1) and A(3) ,
while B(5) is the sum of A(1) , A(3) ,
and A(5) .

Create an array of logical values.

A = [true false true; true true false] A =
1 0 1
1 1 0
Find the cumulative sum of the rows of A .

B = cumsum(A,2) B =
1 1 2
1 2 2 The output is double .

class(B) ans =
double Output Arguments expand all

Cumulative sum array, returned as a vector, matrix, or multidimensional
array of the same size as the input array A .

The class of B is the same as the class of A except
if A is logical , in which case B is double .

More About expand all

The first nonsingleton
dimension is the first dimension of an array whose size is not equal
to 1 .

For example:

If X is a 1-by-n row vector, then
the second dimension is the first nonsingleton dimension of X .

If X is a 1-by-0-by-n empty array,
then the second dimension is the first nonsingleton dimension of X .

If X is a 1-by-1-by-3 array, then
the third dimension is the first nonsingleton dimension of X .

See Also cumprod | diff | prod | sum

Was this topic helpful?