简体   繁体   中英

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 eg 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM