Artur Castiel
Artur Castiel

Reputation: 185

Find which interval a point B is located in Matlab

I have an array of intervals A and I must find a point B that lays in between one of these intervals in A. I cannot loop thru A to find the interval. For ex:

A = [1 3 4 6 10];


1 3
3 4
4 6
6 10

if B =2.3
returns 1

if B = 6.32
return 4

Upvotes: 0

Views: 465

Answers (1)

user6645417
user6645417

Reputation:

Assuming the intervals are in ascending order, you can use find(B < A, 1) - 1 as pointed out in the comments. This will return an empty matrix if B is outside the whole range. If this is undesirable you could add in a check before.

function interval = findInterval(A,B)
    if B > A(1) && B < A(end)
        interval = find(B < A, 1) - 1;
    else
        error('Interval is out of the range specified')
    end
end

Upvotes: 2

Related Questions