AnnaSchumann
AnnaSchumann

Reputation: 1271

Identifying which range a number falls into

Given a set number of ranges:

a =

    32225   52259
    52260   70794
    70795   91459
    91460   95409

And a single value x = 61450 - is there a way to determine within which range x falls without using a loop to check each possibility? The answer in this case would be 2 as 61450 falls within the second range.

Upvotes: 4

Views: 153

Answers (2)

Carl Witthoft
Carl Witthoft

Reputation: 21532

OK, did one :-).

foo = [1;round(1e5*rand(1000,1))];
foop = [ foo(2:end)+1;1e6];

x = 1e5*rand(1,1);
tic
for j = 1:1000

    bardro = find(x >= foo & x <= foop);
end
tocdro = toc;

tic;
for j = 1:1000
    barlui = sum(x >=foo);
end
toclui  = toc;

>> tocdro
tocdro =
    0.0113
>> toclui
toclui =
    0.0047

We have a winner!

Upvotes: 5

ibezito
ibezito

Reputation: 5822

use

res = find(x >= a(1,:) & x < a(2,:));

Upvotes: 9

Related Questions