Conditional cumsum - how to create?

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
the cyclist 2013년 4월 2일
It would be useful if you also described conceptually what you are trying to do.
Eric Sampson
Eric Sampson 2013년 4월 2일
Basically it's a copy of the input, but anytime that the original increases from one val to the next, the output should be hold constant. Sort of like a copy that can only go down :)

댓글을 달려면 로그인하십시오.

 채택된 답변

Roger Stafford
Roger Stafford 2013년 4월 2일

1 개 추천

Try this.
outp = cumsum([inp(1);min(diff(inp),0)]);

댓글 수: 1

Eric Sampson
Eric Sampson 2013년 4월 2일
Ding ding ding! Roger wins, to Matt's detriment :) Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matt Tearle
Matt Tearle 2013년 4월 2일

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

Eric Sampson
Eric Sampson 2013년 4월 2일
Matt that looks promising, but I don't think it generates the same results as the algorithm?
I copy/pasted your code and checked mine against it:
input = rand(100000,1);
tic
output = zeros(size(input));
output(1) = input(1);
for ind = 2:numel(input)
if (input(ind) - input(ind-1)) < 0
output(ind) = input(ind);
else
output(ind) = output(ind-1);
end
end
t1=toc;
tic
d = [true;diff(input)<0];
idx = find(d);
output2 = input(idx(cumsum(d)));
t2=toc;
max(abs(output-output2))
t1/t2
I always seem to get a difference of 0.
Eric Sampson
Eric Sampson 2013년 4월 2일
Argh, I'm sorry Matt. See my revised problem statement. This was clearly a case of 'do what I mean, not what I say' :)
Sean de Wolski
Sean de Wolski 2013년 4월 2일
As you know, the DWIM Toolbox still hasn't been released to the public.
Eric Sampson
Eric Sampson 2013년 4월 2일
Sean, wasn't Loren or Steve supposed to be on that? Slackers.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Deep Learning Toolbox에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by