user1725619
user1725619

Reputation:

Given a number, quickly check which interval it is in?

Assume I have four intervals: [0, 82), [82, 146), [146, 180), [180, 255].

Given a number, let's say 110. I want to quickly check which interval is 110 in, return 1 or 2 or 3 or 4.

I am wondering if MATLAB has existing functions to do rather than comparing the number manually.

Thank you.

Upvotes: 2

Views: 91

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112749

If each interval ends where the next interval begins (as in your example), and if the number is always assured to lie in one of those intervals, you can determine the interval for several numbers at once:

int_bounds = [82 146 180]; %// omit first (0) and last (255) endpoints
numbers = [100 50 146 250];; %// which interval are those numbers in?
result = sum(bsxfun(@ge, numbers(:).', int_bounds(:)), 1)+1;

In this example the result is

result =
     2     1     3     4

Upvotes: 4

Divakar
Divakar

Reputation: 221614

You can use something like this -

intv = [
    0    82;
    82  146;
    146 180;
    180 255]

num = 110

index = find(num>=intv(:,1) & num<intv(:,2))

If the interval array were a row vector: intv = [0 82 146 180 255], you can use -

index = find(num >= intv(1:end-1) & num < intv(2:end))

Or use histc -

index = find(histc(num,intv))

As suggested by @knedlsepp, for more than one input numbers as num, you can use -

[~,indices] = histc(num, intv)

Upvotes: 6

Related Questions