How to find the two nearest values related to a constant

50 ビュー (過去 30 日間)
Juster
Juster 2012 年 5 月 11 日
コメント済み: Nimrod 2018 年 8 月 5 日
Hello to all,
I've to find what are the two values and related indices respect to a constant.
I mean as example; I've a vector and a constant like follow:
a=[1250 2320 3520 4650 5550 6760];
b= 3700;
Therefore I would receive the values 3520 and 4650 and the equivalent indices 3 e 4.
Best regards and thanks in advance.

採用された回答

Thomas
Thomas 2012 年 5 月 11 日
a=[1250 2320 3520 4650 5550 6760];
b= 3700;
% this will work even if 'a' is in random order
d=sort(abs(b-a));
lowest=find(abs(b-a)==d(1))
sec_lowest=find(abs(b-a)==d(2))
  3 件のコメント
Trevor Wright
Trevor Wright 2018 年 2 月 26 日
This doesnt work if d(1) and d(2) are equal, meaning b sits exactly halfway between two values in a. An easy way to solve this is with an if statement.
d=sort(abs(b-a));
if (d(1) == d(2))
vals = find(abs(b-a)==d(1))
lowest = vals(1)
second_lowest = vals(2)
else
lowest=find(abs(b-a)==d(1))
sec_lowest=find(abs(b-a)==d(2))
end
Nimrod
Nimrod 2018 年 8 月 5 日
Tomas, instead of using find, you can use the second output of sort, which is the index for the sorting.

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

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2012 年 5 月 11 日
a=[1250 2320 3520 4650 5550 6760];
b= 3700;
[~,e] = histc(b,a)
out = [a(e+(0:1)) ; e+(0:1)]

Image Analyst
Image Analyst 2012 年 5 月 11 日
firstIndex = find(a<b, 1, 'last')
nextIndex = firstIndex + 1
  2 件のコメント
Philip Bates
Philip Bates 2016 年 5 月 6 日
Only works if a is consistently increasing. If a= e.g. [0, -1, -2, -3] and b = -1.4 then firstIndex = find(a<b, 1, 'last') returns -2 and nextIndex returns -3 which is not correct. You can't simply check absoloute values in case the slope reverses at some point.
Image Analyst
Image Analyst 2016 年 5 月 7 日
Yes, you're right. A much better answer would have been:
a=[1250 2320 3520 4650 5550 6760]
b= 3700
differences = abs(a-b)
[minDiff, indexOfMinDiff] = min(differences);
closestValue = a(indexOfMinDiff);
message = sprintf('The value in "a" closest to "b" is %d', closestValue);
uiwait(helpdlg(message));

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by