Binary Search of Elements lying within an Interval

Search all elements (in a sorted vector of n elem.) that lie within an interval. It runs in log(n).
759 Downloads
Updated 15 Apr 2011

View License

Search the elements that are lying within a specified interval.
Search the indexes of all elements in x (sorted vector of n elements) that lie within the interval.
The algorithm uses binary searches, thus it runs in log(n)
INPUT:
x: vector of numeric values sorted in ascending order
(e.g. 2,7,20,...120)
ref: numeric value of the reference point (center of the interval)
tol: numeric value corresponding to 1/2 of the width of the interval
The fourth input argument: numeric value (optional). Allows to define the maximum number of elements of x that can lie within the specified interval. This is useful in order to speed up the search.

OUTPUT:
indexes: indexes of elements of x which lie within the interval [ref-tol ref+tol]
If ref is not found in x then indexes is empty.

Cite As

Roberto Olmi (2024). Binary Search of Elements lying within an Interval (https://www.mathworks.com/matlabcentral/fileexchange/26680-binary-search-of-elements-lying-within-an-interval), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2008a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Operators and Elementary Operations in Help Center and MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.4.0.0

Fixed a bug with unsigned input arrays (e.g. uint16). Thanks to Igor Varfolomeev for the comment.

1.3.0.0

- Added lines 38-55 to consider the case when lower bound is less than the min(x) or the upper bound is more than the max(x)
- Reinforced the conditions in line 93 and in line 117 in order to avoid an error when (to-1)==0 or (from+1)>length(x)

1.1.0.0

Bug fixed

1.0.0.0