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
2013 年 4 月 2 日
It would be useful if you also described conceptually what you are trying to do.
Eric Sampson
2013 年 4 月 2 日
採用された回答
その他の回答 (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 件のコメント
Eric Sampson
2013 年 4 月 2 日
Matt Tearle
2013 年 4 月 2 日
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
2013 年 4 月 2 日
Sean de Wolski
2013 年 4 月 2 日
As you know, the DWIM Toolbox still hasn't been released to the public.
Eric Sampson
2013 年 4 月 2 日
カテゴリ
ヘルプ センター および File Exchange で Deep Learning Toolbox についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!