nearestpoint(x, y, m)

NEARESTPOINT - find the nearest value in another vector
7.4K Downloads
Updated 20 Dec 2017

View License

NEARESTPOINT - find the nearest value in another vector

IND = NEARESTPOINT(X,Y) finds the value in Y which is the closest to each value in X, so that abs(Xi-Yk) => abs(Xi-Yj) when k is not equal to j.
IND contains the indices of each of these points.
Example:
NEARESTPOINT([1 4 12],[0 3]) -> [1 2 2]
[IND,D] = ... also returns the absolute distances in D,that is D == abs(X - Y(IND))
NEARESTPOINT(X, Y, M) specifies the operation mode M:
1) 'nearest' : default, same as above
2) 'previous': find the points in Y that just precedes a point in X
NEARESTPOINT([1 4 12],[0 3],'previous') -> [1 1 1]
3) 'next' : find the points in Y that directly follow a point in X
NEARESTPOINT([1 4 12],[0 3],'next') -> [2 NaN NaN]

If there is no previous or next point in Y for a point X(i), IND(i)
will be NaN.

X and Y may be unsorted.

This function is quite fast, and especially suited for large arrays with
time data. For instance, X and Y may be the times of two separate events, like simple and complex spike data of a neurophysiological study.
Run NEARESTPOINT('test') to see a test of it's running time

Cite As

Jos (10584) (2024). nearestpoint(x, y, m) (https://www.mathworks.com/matlabcentral/fileexchange/8939-nearestpoint-x-y-m), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2017b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Spatial Search 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
4.2.0.0

updated for newer NL releases

4.1.0.0

fixed error mentioned by Julian (D was requested but no nearest point was found).

1.1.0.0

Updated function to avoid errors when called with NaNs and empty variables. Thanks Drew.

1.0.0.0

corrected error when using 'prev' option