Vectorise for loop checking for values in intervals

Hi there,
I have the following datasets:
a =
5
7
8
9
10
12
b =
3 6
11 13
20 22
I want to look if each element of a is in any of the intervals in b, without a for-loop. The for loop is:
result = zeros(length(a),1);
for i =1:length(a)
for j= 1:size(b,1)
if a(i)>=b(j,1) && a(i)<= b(j,2)
result(i) = 1
break;
end
end
end
I am hoping to speed this up.

 採用された回答

Guillaume
Guillaume 2018 年 1 月 12 日

0 投票

If using R2016b or later:
result = any(a >= b(:, 1).' & a <= b(:, 2).', 2)
Otherwise
result = any(bsxfun(@ge, a, b(:, 1).') & bxfun(@le, a, b(:, 2).'), 2)

1 件のコメント

TJ
TJ 2018 年 1 月 12 日
Works great. Thank you!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

TJ
2018 年 1 月 12 日

コメント済み:

TJ
2018 年 1 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by