MATLAB Answers


How can we perform cumulative sums along a particular directions in matrices?

Asked by Simon
on 20 Jun 2013

Hi all,

I'm actually trying to perform cumulative sums along arbitrary directions in images. For sure a simple sum can be done with the radon() function, however I need to keep track of an integral, thus requiring a cumsum(). I've tried to use imrotate() and then cumsum() but initial and final images don't have the same dimensions anymore, causing another problem.

Any help would be really appreciated!



  1 Comment

It might be helpful to give a small example or two of inputs and expected outputs.

Log in to comment.

2 Answers

Answer by Image Analyst
on 20 Jun 2013
 Accepted Answer

I pretty sure there's nothing built in to MATLAB or the Image Processing Toolbox to do that. You'd have to program it up yourself. Sorry, but it's just such a unique requirement that there's no code yet to do that as far as I know. It can be done though. You might find improfile() helpful as you scan across, at one pixel spacings or whatever you require, getting profiles and calling cumsum().


Alright, this is what I thought. I came up recently with something that seems to be a pretty good approximation of what I need. It looks like the following lines:

% Creating Image


% Rotating frame at angle phi


% Performing cumulative sum


% Returning back to reference frame


Then I crop the final image B with imcrop() since two calls of imrotate() doubles image dimensions. It can be extended to image stacks by simply operating a for-loop on imcrop().

It seems to work well, but if anyone has a better idea, please let me know!

Thanks for the proposal,


Sounds reasonable to me. If it works well, as you say, then use it.

Log in to comment.

Answer by the cyclist
on 20 Jun 2013

Direct from the documentation:

B = cumsum(A,dim) returns the cumulative sum of the elements along dimension dim.

Does that help?


A = magic(5);
B_down   = cumsum(A,1); % Cumulative sum down columns (the default)
B_across = cumsum(A,2); % Cumulative sum across the rows

  1 Comment

No, it is not that simple, I think there is a misunderstanding about the question.

I want to do a cumsum at an arbitrary projection angle. The radon() does exactly that, but is not cumulative. I need something of the form:

A=phantom(); B=cumsum_dir(A,phi);

Where the cumsum() is executed at angle phi from the reference frame.

I hope this is clearer.

Thanks for the answer,


Log in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today