Vectorize nested for loops
古いコメントを表示
Hi, I would like to vectorize the following loop, have tried generating indices and but so far been successful.
a = any 1D vector
N = some value
for i=1:length(a)
for j=(i+1):length(a)
if(a(i)-a(j) > N)
disp('Far');
end
end
end
Does anyone have any ideas on this ?
2 件のコメント
Guillaume
2018 年 1 月 31 日
The ability of vectorising loops depends solely on the do something. So if you don't tell us what it is, we can't answer your question.
Balkrishna Patankar
2018 年 1 月 31 日
回答 (1 件)
Guillaume
2018 年 1 月 31 日
Your example is trivially vectorised:
%R2016b or later:
isgreater = (a - a.') > N;
%any version:
isgreater = bsxfun(@minus, a, a.') > N;
isgreater(r, c) is true (1) when a(r)-a(c) > N
3 件のコメント
Balkrishna Patankar
2018 年 2 月 1 日
Indeed, my answer was equivalent to having the j loop starting at 1 instead of i+1. The upper triangle of that isgreater matrix is the exact equivalent of your loops, so:
isgreater = triu((a - a.') > N, 1)
Balkrishna Patankar
2018 年 2 月 2 日
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!