cumsum

Symbolic cumulative sum

Syntax

Description

example

cumsum(A) returns an array the same size as 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 of each column of A.

example

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

Examples

Cumulative Sum of a Vector

Create vector V 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 a Symbolic Matrix

Create matrix A containing symbolic numbers and matrix B containing symbolic expressions:

syms x y
A = sym([0, 1, 2; 3, 4, 5; 1, 2, 3])
B = [x, 2*x + 1, 3*x + 2; 1/y, y, 2*y]
A =
[ 0, 1, 2]
[ 3, 4, 5]
[ 1, 2, 3]

B =
[   x, 2*x + 1, 3*x + 2]
[ 1/y,       y,     2*y]

Compute the cumulative sums of elements of A and B. By default, cumsum returns the cumulative sum of each column:

sumA = cumsum(A)
sumB = cumsum(B)
sumA =
[ 0, 1,  2]
[ 3, 5,  7]
[ 4, 7, 10]
 
sumB =
[       x,     2*x + 1,       3*x + 2]
[ x + 1/y, 2*x + y + 1, 3*x + 2*y + 2]

Cumulative Sum of Each Row in a Symbolic Matrix

Create matrix A containing symbolic numbers and matrix B containing symbolic expressions:

syms x y
A = sym([0, 1, 2; 3, 4, 5; 1, 2, 3])
B = [x, 2*x + 1, 3*x + 2; 1/y, y, 2*y]
A =
[ 0, 1, 2]
[ 3, 4, 5]
[ 1, 2, 3]

B =
[   x, 2*x + 1, 3*x + 2]
[ 1/y,       y,     2*y]

Compute the cumulative sum of each row of matrices A and B:

sumA = cumsum(A,2)
sumB = cumsum(B,2)
sumA =
[ 0, 1,  3]
[ 3, 7, 12]
[ 1, 3,  6]
 
sumB =
[   x, 3*x + 1,   6*x + 3]
[ 1/y, y + 1/y, 3*y + 1/y]

Input Arguments

expand all

A — Input arraysymbolic vector | symbolic matrix

Input array, specified as a vector or matrix.

dim — Dimension to operate alongpositive integer

Dimension to operate along, specified as a positive integer. The default value is 1.

cumsum returns A if dim is greater than ndims(A).

See Also

| | | | |

Was this topic helpful?