1

What is an efficient way to find the smallest distance from a number lets say 2.5 in an array A in MATLAB?

The problem I have is that while I use the function min

     min(abs(A - 2.5))

I get an answer e.g 0.0053 I do not know what is the index of the number that gives the smallest difference after the subtraction.

I tried to add again the number so I get 2.5053 and when I try to do

     find(2.5053) 

I get:

     Empty matrix: 1-by-0
Roney Michael
  • 3,964
  • 5
  • 30
  • 45
Spyros
  • 289
  • 1
  • 6
  • 20

1 Answers1

6

Just use the second output of min:

[value, index] = min(abs(A - 2.5));

Adding the number and then using find has several problems:

  1. It's less efficient.
  2. How do you know if you have to add or subtract? You are using abs.
  3. Comparing doubles for equality is not usually a good idea, because of finite precision.
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147