Open In App

How to Calculate Cumulative Product in MATLAB

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

Now we will discuss the above syntaxes in detail:



B = cumprod(A)

Example 1:




% Input vector
A = 2:8;
 
B = cumprod(A);
 
% Displays cumulative
% products of A
disp(B)

Output :

Example 2:




% Input matrix
A = [1 4 7; 2 5 8; 3 6 9];
disp("Matrix :")
disp(A)
 
B = cumprod(A);
% Display cumulative product of matrix A
disp("Cumulative product :")
disp(B)

Output :

B = cumprod(A,dim)




% input matrix
A = [1 3 5; 2 4 6];
disp("Matrix :")
disp(A)
 
% Cumulative product along each
% row from left to right
B = cumprod(A,2);
disp("Cumulative product :")
disp(B);

Output :
 

B = cumprod(___,direction)




% input matrix
A = [1 3 5; 2 4 6];
disp("Matrix :")
disp(A)
 
% Cumulative product of A along each row
% starting from right to left
B = cumprod(A,2,'reverse');
disp("Cumulative product :")
disp(B)

Output :

B = cumprod(___,nanflag)

Note: NaN * number = NaN




% Input vector
A = [3 5 NaN 9 0 NaN];
disp("Vector :");
disp(A);
 
% Including NaN values
B = cumprod(A,'includenan');
disp("Cumulative product Include NaN :");
disp(B);
 
% Excluding NaN values
B = cumprod(A,'omitnan');
disp("Cumulative product Exclude NaN :");
disp(B);

 Output :


Article Tags :