# Find nearest value to specific number

1.911 visualizzazioni (ultimi 30 giorni)
Jens Keijser il 5 Gen 2018
Commentato: Andres Felipe il 1 Dic 2023
Hello, I have an array with 20 values of steps per minute. I already know that the perfect outcome of one of these values is 33spm. But unfortunately 33spm is not in the array 34.8 is which is the closest to 33. What is the code to find the value closest to 33?
ClosestValue = 34.8
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Birdman il 5 Gen 2018
Modificato: Birdman il 5 Gen 2018
Try the following approach:
a=[34.8 31 29 26.7 39.5];%dummy data
n=33;
[val,idx]=min(abs(a-n));
minVal=a(idx)
Edit after Jan's warning(multiple values)
a=[34.8 31.2 29 26.7 39.5];%dummy data
n=33;
[~,~,idx]=unique(round(abs(a-n)),'stable');
minVal=a(idx==1)
##### 17 CommentiMostra 15 commenti meno recentiNascondi 15 commenti meno recenti
Umesh Gautam il 29 Ago 2023
Modificato: Umesh Gautam il 29 Ago 2023
Thanks @Birdman, code is working great...even one can find the array of values.
Andres Felipe il 1 Dic 2023
Thankss.

Accedi per commentare.

### Più risposte (2)

Walter Roberson il 5 Gen 2018
Use interp1 with 'nearest'
Or since the vector is small abs() the difference between the probe and the fixed values and min() that and take the second output of min() and use that to index the fixed values. This is not as convenient as interp1 but should be faster
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Atique Barudgar il 8 Nov 2019
I am not clear how Birdman SIr's answer came
when idx =1
then how a(idx)=34.8
I didnt got how and what is idx
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Nicolas Hofer il 8 Ott 2021
idx stand for index. search for indexing in matlab for further explanation

Accedi per commentare.

### Categorie

Scopri di più su Dynamic System Models in Help Center e File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by