0

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?

jub0bs
  • 60,866
  • 25
  • 183
  • 186
  • @rayreng Apologies. I should have checked for dupes first. – jub0bs Aug 13 '15 at 15:55
  • @Jubobs - No problem :) Sometimes it's faster to answer than find a duplicate... such as this example: http://stackoverflow.com/questions/31992090/extracting-the-corresponding-value-of-a-rank-vector-in-matlab/31992458#31992458 - we've seen **many** questions like this, but can't nail a good enough duplicate. If I was in your situation, I would have also answered if I didn't know that there was a suitable duplicate. FWIW, I've upvoted your answer. – rayryeng Aug 13 '15 at 16:34

2 Answers2

2

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).

jub0bs
  • 60,866
  • 25
  • 183
  • 186
0

I think this should do it:

[~, i] = min(abs(A - (-90)));

This will take the difference of each element in A with the number you supply. min will then find the minimum, and return the index of it.

Matt
  • 4,029
  • 3
  • 20
  • 37
  • 1
    Yes, this works if I add abs. So if it turns into: [~, i] = min(abs(A - (-90))); the first part returns the value (which is not needed) and the i return the position. Thanks – Eliott Roocroft Aug 13 '15 at 15:46
  • @Matt After your edit, the main text of your answer no longer matches the code: absolute value `~=` difference. – jub0bs Aug 13 '15 at 15:54