Search code examples
arraysmatlababsolute-value

How can I locate the element of an array that is nearest to some number?


I have an array A, e.g.

A = [-79.0732  -82.1919  -85.0432  -87.0406  -90.0102  -92.6745]

and some number x (e.g. -90), and I want to find the index of the element in the array that is closest (in absolute value) to x.

In my example, the element closest element of A to x is -90.0102, i.e. the 5th element of array A. How can I, in general, compute the index of the element that is nearest to x?


Solution

  • If x is the value of interest and A is the array, run

    [~, inearest] = min(abs(A - x));
    

    Then inearest will contain the index of the element of array A that is closest to x (in absolute value).