Filter löschen
Filter löschen

How to find the two nearest values related to a constant

53 Ansichten (letzte 30 Tage)
Juster
Juster am 11 Mai 2012
Kommentiert: Nimrod am 5 Aug. 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.

Akzeptierte Antwort

Thomas
Thomas am 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 Kommentare
Trevor Wright
Trevor Wright am 26 Feb. 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 am 5 Aug. 2018
Tomas, instead of using find, you can use the second output of sort, which is the index for the sorting.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by