Open In App

Cumulative Sum in MATLAB

The cumulative sum of a sequence is a running sums or partial sums of a sequence.

The cumulative sums of the sequence {a,b,c,…}, are a, a+b, a+b+c, ….



MATLAB allows us to calculate the cumulative sum of a vector, matrix using cumsum() method. Different syntax of cumsum() method are:

Let us discuss the above syntax in detail:



cumsum(A)

Example 1:




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

 
Output :
 

 Example 2:




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

 Output :

cumsum(A,dim)




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

 Output :

cumsum(___,direction)




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

 Output :

cumsum(___,nanflag)

Note : NaN + number = NaN




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

Output :


Article Tags :