Conditional cumsum - how to create?
조회 수: 3 (최근 30일)
이전 댓글 표시
This is probably easy, but my brain isn't working today...
How can you do the following operation in a vectorized way? I'd think it should be possible with some combination of cumsum, diff & logical indexing:
input = rand(10,1);
output = zeros(size(input);
output(1) = input(1);
for ind = 2:numel(input)
dif = input(ind) - input(ind-1);
if dif < 0
output(ind) = output(ind-1) + dif;
else
output(ind) = output(ind-1);
end
end
댓글 수: 2
the cyclist
2013년 4월 2일
It would be useful if you also described conceptually what you are trying to do.
채택된 답변
추가 답변 (1개)
Matt Tearle
2013년 4월 2일
There may be better ways, but this works:
d = [true;diff(input)<0];
idx = find(d);
output = input(idx(cumsum(d)));
When the array is large enough, there's a pretty decent speedup (~50x)
댓글 수: 5
참고 항목
카테고리
Help Center 및 File Exchange에서 Bartlett에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!