Spyros
Spyros

Reputation: 289

Find the minimum distance to a number from the elements of an array in MATLAB

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

Upvotes: 1

Views: 1220

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112669

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.

Upvotes: 6

Related Questions