필터 지우기
필터 지우기

Two variable Cumulative Sum calculation

조회 수: 4 (최근 30일)
frankovaT
frankovaT 2019년 6월 27일
댓글: frankovaT 2019년 6월 29일
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