File Exchange

image thumbnail

Closest

version 1.1 (1.17 KB) by

Finds the value in an array X closest to the scalar b.

0 Downloads

Updated

View License

Given a vector or matrix X, CLOSEST(X,b) finds the element in X that is nearest to the scalar b.

Example:

>> X = [-1 -2 6.14 9];
>> b = pi;
>> c = closest(X,b)

c =
   6.14

Comments and Ratings (2)

Richard Crozier

John D'Errics's excellent ipdm http://www.mathworks.co.uk/matlabcentral/fileexchange/18937-ipdm-inter-point-distance-matrix is more advanced, and supports lots of distance metrics, use the 'nearestto' option to get similar results to your funtion.

Jos (10584)

Jos (10584) (view profile)

[~,idx] = min(abs(X(:)-b))
c = X(idx)

would do.

Updates

1.1

simpler algorithm, thanks to comment

MATLAB Release
MATLAB 7.14 (R2012a)
Tags Add Tags
Acknowledgements

Inspired: near2

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video