Effacer les filtres
Effacer les filtres

How to find the two nearest values related to a constant

53 vues (au cours des 30 derniers jours)
Juster
Juster le 11 Mai 2012
Commenté : Nimrod le 5 Août 2018
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.

Réponse acceptée

Thomas
Thomas le 11 Mai 2012
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 commentaires
Trevor Wright
Trevor Wright le 26 Fév 2018
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 le 5 Août 2018
Tomas, instead of using find, you can use the second output of sort, which is the index for the sorting.

Connectez-vous pour commenter.

Plus de réponses (2)

Andrei Bobrov
Andrei Bobrov le 11 Mai 2012
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 le 11 Mai 2012
firstIndex = find(a<b, 1, 'last')
nextIndex = firstIndex + 1
  2 commentaires
Philip Bates
Philip Bates le 6 Mai 2016
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 le 7 Mai 2016
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));

Connectez-vous pour commenter.

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by