Two variable Cumulative Sum calculation

6 views (last 30 days)
I am having 5 by 5 matrix. I want to make a cumulative sum from each variable As an example:
The A(3,2) Argument would be the sum of all the arguemts before this argument and this argument, like:
A(3,2)=A(1,1)+A(2,1)+A(3,1)+A(1,2)+A(2,2)+A(3,2)
I want to make a for loop to go on each argument
for i = 1:5
For j=1:5
Any ideas on how I can do that?

Accepted Answer

Jon
Jon on 27 Jun 2019
If I understand your description corrrectly, I think this does what you want, no loops needed.
B = cumsum(cumsum(A,1),2)
  5 Comments
Jon
Jon on 28 Jun 2019
As you were interested, I've attached a function which I just wrote that computes the cumulative 2d sum using for loops. I did a little bit of testing to compare run times (using tic,toc) for a large array (10^4 x 10^4) using this double loop compared to the one line B = cumsum(cumsum(A,1),2). It seemed that it took almost twice as long using the double loop.
function B = cumsum2d(A)
%CUMSUM2D Compute cumulative sum over 2d array
% B = cumsum2d(A) computes 2-d matrix B whose elements are
% the cumulative sum over elements of 2-d matrix A
% such that B(i,j) is the sum of all elements of A whose row and
% column indices are less than or equal to i and j respectively
% get the total number of rows and columns, we need these for end condition
% on loops
[numRows,numCols] = size(A);
% preallocate matrix the same size as A to hold result
B = zeros(numRows,numCols);
% loop through rows and columns accumulating totals
for jCol = 1:numCols
% initialize cumulative sum of elements in this column
sumThisCol = 0;
for iRow = 1:numRows
% update the sum of elements in the current column
sumThisCol = sumThisCol + A(iRow,jCol);
% update the cumulative sum of all of the elements to the left and
% above this element (inclusive)
% (need branch to handle special case of first column since there
% isn't anything to the left of that)
if jCol > 1
% in the interior, there is a column to the left of this one
B(iRow,jCol) = B(iRow,jCol - 1) + sumThisCol;
else
% this is the first column, there is nothing to the left of it
% to add
B(iRow,jCol) = sumThisCol;
end
end
end
frankovaT
frankovaT on 29 Jun 2019
Dear Jonathan
Thank you very much for sending me this as well. I truly appreciate your effort. This helps alot.
Best

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!