0

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
Artur Castiel
  • 185
  • 1
  • 15
  • Are the numbers in `A` always in ascending order? Because then it's just `find(A < B, 1, 'last')` – Dan Aug 15 '16 at 15:49
  • 1
    `find(B < A, 1) - 1` – Chris Taylor Aug 15 '16 at 15:51
  • Take in account that the intervals can be closed to the left or to the right, so you might want to use the `<` or the `<=` operator depending on the desired behaviour. Also if the value of B falls outside the ranges extra code might be needed. –  Aug 15 '16 at 15:55
  • that works. you guys could answer the question so I could close it – Artur Castiel Aug 15 '16 at 16:09

1 Answers1

2

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