Vectorizing a loop for cumulative sum with reset
조회 수: 4 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Lars Nelson
2023년 4월 26일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!