B = cumsum(___,direction) specifies
the direction using any of the previous syntaxes. For instance, cumsum(A,2,'reverse') returns
the cumulative sum within the rows of A by working
from end to beginning of the second dimension.

Examples

Cumulative Sum of Vector

Create a vector and find the cumulative sum
of its elements.

V = 1./factorial(sym([1:5]))
sum_V = cumsum(V)

V =
[ 1, 1/2, 1/6, 1/24, 1/120]
sum_V =
[ 1, 3/2, 5/3, 41/24, 103/60]

Cumulative Sum of Each Column in Symbolic Matrix

Create matrix a 4-by-4 symbolic matrix A all
elements of which equal 1.

A = sym(ones(4,4))

A =
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]

Compute the cumulative sum of elements of A.
By default, cumsum returns the cumulative sum
of each column.

sumA = cumsum(A)

sumA =
[ 1, 1, 1, 1]
[ 2, 2, 2, 2]
[ 3, 3, 3, 3]
[ 4, 4, 4, 4]

Cumulative Sum of Each Row in Symbolic Matrix

Create matrix a 4-by-4 symbolic matrix A all
elements of which equal 1.

A = sym(ones(4,4))

A =
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]

Compute the cumulative sum of each row of the matrix A.

sumA = cumsum(A,2)

sumA =
[ 1, 2, 3, 4]
[ 1, 2, 3, 4]
[ 1, 2, 3, 4]
[ 1, 2, 3, 4]

Reverse Cumulative Sum

Create matrix a 4-by-4 symbolic matrix, all
elements of which equal 1.

A = sym(ones(4,4))

A =
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]

Calculate the cumulative sum along the columns in both directions.
Specify the 'reverse' option to work from right
to left in each row.

This website uses cookies to improve your user experience, personalize content and ads, and analyze website traffic. By continuing to use this website, you consent to our use of cookies. Please see our Privacy Policy to learn more about cookies and how to change your settings.