フィルターのクリア

Find nearest value to specific number

1,224 ビュー (過去 30 日間)
Jens Keijser
Jens Keijser 2018 年 1 月 5 日
コメント済み: Andres Felipe 2023 年 12 月 1 日
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?
The ideal answer would be:
ClosestValue = 34.8
Could someone help me please?

採用された回答

Birdman
Birdman 2018 年 1 月 5 日
編集済み: Birdman 2018 年 1 月 5 日
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 件のコメント
Umesh Gautam
Umesh Gautam 2023 年 8 月 29 日
編集済み: Umesh Gautam 2023 年 8 月 29 日
Thanks @Birdman, code is working great...even one can find the array of values.
Andres Felipe
Andres Felipe 2023 年 12 月 1 日
Thankss.

サインインしてコメントする。

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2018 年 1 月 5 日
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

Atique Barudgar
Atique Barudgar 2019 年 11 月 8 日
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 件のコメント
Nicolas Hofer
Nicolas Hofer 2021 年 10 月 8 日
idx stand for index. search for indexing in matlab for further explanation

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by