File Exchange

image thumbnail


version (1.24 KB) by Tom O'Haver
Returns the index and the value of the element of vector x that is closest to val


Updated 25 Oct 2006

View License

function [index,closestval]=val2ind(x,val)
A very simple 3-line function that returns the index and the value of the element of vector x that is closest to a particular numerical value.
If more than one element is equally close, returns vectors of indicies and values.
Examples: If x=[1 2 4 3 5 9 6 4 5 3 1], then val2ind(x,6)=7 and val2ind(x,5.1)=[5 9]
[indices values]=val2ind(x,3.3) returns indices = [4 10] and values = [3 3].

Sample use: to determine the index and value of an element of a vector from the x,y values obtained by clicking on a plot of that vector using ginput.

Cite As

Tom O'Haver (2021). val2ind (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (1)

Jos x@y.z

As it is this is just a very simple textbook example. To be useful in general, it should be able to handle ND matrices and it should treat NaNs effectively.

I tended to give this submission a rating of 3 stars, since this tackles a problem many users are faced with. However, this function does not check for common input errors. Moreover, there are already better, more general solutions available here on the FEX. Search for distance, minimum, ...

MATLAB Release Compatibility
Created with R13
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!