Code covered by the BSD License
06 Jun 2013
07 Jun 2013)
Finds the value in an array X closest to the scalar b.
Watch this File
Given a vector or matrix X, CLOSEST(X,b) finds the element in X that is nearest to the scalar b.
>> X = [-1 -2 6.14 9];
>> b = pi;
>> c = closest(X,b)
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.
[~,idx] = min(abs(X(:)-b))
c = X(idx)
simpler algorithm, thanks to comment