# Vectorizing a loop for cumulative sum with reset

5 views (last 30 days)
cr on 26 Apr 2023
Answered: Lars Nelson on 26 Apr 2023
The lines below work fine to compute cumulative sum on a 1D logical array ('s') such that the summation resets to zero whereever the element in 's' is zero. Question is, how can this be vectorised to avoid loop.
r(1) = s(1); %s is the source vector, r is the result
for i = 2:length(s)
r(i) = (r(i-1) + s(i))*s(i);
end
Thanks.
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Answers (1)

Lars Nelson on 26 Apr 2023
Unfortunately, because each value in vector r depends on the previous value in r, I do not think that there is a way to vectorize this code and you will have to use a loop.
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Categories

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

R2023a

### Community Treasure Hunt

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

Start Hunting!