How to Calculate Cumulative Product in MATLAB
Last Updated :
04 Jul, 2022
The cumulative product of a sequence is a running products or partial products of a sequence
The cumulative products of the sequence {a,b,c,…}, are a, a*b, a*b*c, ….
Matlab allows us to calculate the cumulative product of a vector, matrix using cumprod() method. Different syntaxes of cumprod() method are
- B = cumprod(A)
- B = cumprod(A,dim)
- B = cumsprod(___,direction)
- B = cumprod(___,nanflag)
Now we will discuss the above syntaxes in detail:
B = cumprod(A)
- The method returns the cumulative product of A starting at the beginning of array A.
- If A is a vector, then it returns the cumulative product of sequence A
- If A is a matrix, then it returns the cumulative product along each column of A.
Example 1:
Matlab
A = 2:8;
B = cumprod(A);
disp(B)
|
Output :
Example 2:
Matlab
A = [1 4 7; 2 5 8; 3 6 9];
disp( "Matrix :" )
disp(A)
B = cumprod(A);
disp( "Cumulative product :" )
disp(B)
|
Output :
B = cumprod(A,dim)
- Returns the cumulative product of matrix A along with each dim.
- dim takes two values 1 or 2.
- dim = 1, refers to along each column.
- dim = 2, refers along each row.
Matlab
A = [1 3 5; 2 4 6];
disp( "Matrix :" )
disp(A)
B = cumprod(A,2);
disp( "Cumulative product :" )
disp(B);
|
Output :
B = cumprod(___,direction)
- Returns the cumulative product of the input vector or matrix in the given direction.
- direction takes two values ‘forward’ or ‘reverse’
- If the direction is ‘reverse’, then calculates cumulative product in reverse i.e if we are considering matrix along each column, then it returns cumulative product starting from bottom to top of each column.
Matlab
A = [1 3 5; 2 4 6];
disp( "Matrix :" )
disp(A)
B = cumprod(A,2, 'reverse' );
disp( "Cumulative product :" )
disp(B)
|
Output :
B = cumprod(___,nanflag)
- nanflag value decides whether to include or exclude NaN value of the vector in cumulative product or not.
- nanflag takes two values ‘includenan’ or ‘omitnan’ corresponds to including NaN elements and excluding NaN elements respectively.
- ‘omitNaN’ considers NaN values as 1.
Note: NaN * number = NaN
Matlab
A = [3 5 NaN 9 0 NaN];
disp( "Vector :" );
disp(A);
B = cumprod(A, 'includenan' );
disp( "Cumulative product Include NaN :" );
disp(B);
B = cumprod(A, 'omitnan' );
disp( "Cumulative product Exclude NaN :" );
disp(B);
|
Output :
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...