How to calculate a cumulative sum in a loop?

3 views (last 30 days)
I have a loop that looks like this:
for a = 1: 9
for b = 1 : 1000
for c = 1 : 1000
image = myimage_bands(b, c, a);
new_image = image * 5;
I am trying to find the cumulative sum of my variable 'new_image', as it goes through the loop. I've tried cumsum, but it doesn't work.
Any ideas are appreciated. Thanks!
  1 Comment
Azzi Abdelmalek
Azzi Abdelmalek on 20 Nov 2013
Edited: Azzi Abdelmalek on 20 Nov 2013
There is no cumulative sum in your code, can you explain what you want?

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 21 Nov 2013
Before the loop,
image_sum = [];
inside the loop after you have calculated new_image,
if isempty(image_sum)
image_sum = new_image;
image_sum(end+1) = image_sum(end) + new_image;
Sandy on 21 Nov 2013
Thank you! I have another question though. How would I change the code if my variable new_image was a matrix (6 x 6)?
Walter Roberson
Walter Roberson on 21 Nov 2013
image_sum(:,:,end+1) = image_sum(:,:,end) + new_image;

Sign in to comment.

More Answers (0)


Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!