フィルターのクリア

Vectorization of a for loop

2 ビュー (過去 30 日間)
jpedro
jpedro 2015 年 11 月 9 日
編集済み: Guillaume 2015 年 11 月 10 日
Hello,
I am trying to eliminate the loop and vectorise this piece of code. Any ideas?
for k = 1:(length(P)-2)
if ((P(k+1)-P(k)>0)&&(P(k+2)-P(k+1)<0));
B(k+1) = 1;
end
end
Thanks

回答 (2 件)

Peter O
Peter O 2015 年 11 月 9 日
v = 1:length(P)-2;
ix = find( ((P(v+1) - P(v)) > 0) & ((P(v+2) - P(v+1)) < 0) ) + 1;
B2(ix) = 1;
  1 件のコメント
jpedro
jpedro 2015 年 11 月 10 日
Hello Peter,
Thanks for your answer, but that code doesn't give the same results as the for above

サインインしてコメントする。


Guillaume
Guillaume 2015 年 11 月 10 日
編集済み: Guillaume 2015 年 11 月 10 日
Well, P(k+1)-P(k) can be obtained in a vectorised way with the diff function, so, assuming that by default B(k) is zero:
B = diff(P(1:end-1)) > 0 & diff(P(2:end)) < 0 %no need to preinitialise B
If by default, B(k) is something else:
B(diff(P(1:end-1)) > 0 & diff(P(2:end)) < 0) = 1; %B must be preinitialised

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by