Two variable Cumulative Sum calculation

5 次查看(过去 30 天)
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?

采纳的回答

Jon
Jon 2019-6-27
If I understand your description corrrectly, I think this does what you want, no loops needed.
B = cumsum(cumsum(A,1),2)
  5 个评论
Jon
Jon 2019-6-28
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 2019-6-29
Dear Jonathan
Thank you very much for sending me this as well. I truly appreciate your effort. This helps alot.
Best

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by