How to find the two nearest values related to a constant

49 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by