Conditional cumsum - how to create?

2 vues (au cours des 30 derniers jours)
Eric Sampson
Eric Sampson le 2 Avr 2013
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 commentaires
the cyclist
the cyclist le 2 Avr 2013
It would be useful if you also described conceptually what you are trying to do.
Eric Sampson
Eric Sampson le 2 Avr 2013
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 :)

Connectez-vous pour commenter.

Réponse acceptée

Roger Stafford
Roger Stafford le 2 Avr 2013
Try this.
outp = cumsum([inp(1);min(diff(inp),0)]);
  1 commentaire
Eric Sampson
Eric Sampson le 2 Avr 2013
Ding ding ding! Roger wins, to Matt's detriment :) Thanks!

Connectez-vous pour commenter.

Plus de réponses (1)

Matt Tearle
Matt Tearle le 2 Avr 2013
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 commentaires
Sean de Wolski
Sean de Wolski le 2 Avr 2013
As you know, the DWIM Toolbox still hasn't been released to the public.
Eric Sampson
Eric Sampson le 2 Avr 2013
Sean, wasn't Loren or Steve supposed to be on that? Slackers.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Deep Learning Toolbox dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by