How to find the two nearest values related to a constant

50 visualizaciones (últimos 30 días)
Juster
Juster el 11 de Mayo de 2012
Comentada: Nimrod el 5 de Ag. de 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.

Respuesta aceptada

Thomas
Thomas el 11 de Mayo de 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 comentarios
Trevor Wright
Trevor Wright el 26 de Feb. de 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 el 5 de Ag. de 2018
Tomas, instead of using find, you can use the second output of sort, which is the index for the sorting.

Iniciar sesión para comentar.

Más respuestas (2)

Andrei Bobrov
Andrei Bobrov el 11 de Mayo de 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 el 11 de Mayo de 2012
firstIndex = find(a<b, 1, 'last')
nextIndex = firstIndex + 1
  2 comentarios
Philip Bates
Philip Bates el 6 de Mayo de 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 el 7 de Mayo de 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));

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by