How to select the first appearance of the minimum value?
2 views (last 30 days)
Show older comments
Daniel Vazquez Pombo
on 24 Jun 2020
Edited: Daniel Vazquez Pombo
on 25 Jun 2020
I have a vector (A) with some numbers, then I want to find which one is the closest to the value b.
A=[-0.1000 -0.0800 -0.0600 -0.0400 -0.0200 0 0.0200 0.0400 0.0600 0.0800 0.1000];%dummy data
b=-0.03;
In this case, both -0.04 and -0.02 are at the same distance, then I want to select -0.04
I tried several methods, but for some reason, Matlab completely ignores the possibility of -0.04
nearest=b %initialisation
difference= abs(A-b)
minimum=min(difference)
for i=1:length(A)
if minimum == difference(i) %technically it should enter this if twice, however, it doesnt enter once!
nearest=A(i)
end
end
nearest
I am so frustrated, technically, this line of code should return all the appereances, so two, but it only returns one!
[row,col] = find(difference==val)
I will really appreciate some help with this. Clearly I am doing something wrong, but I have no clue what.
2 Comments
jessupj
on 24 Jun 2020
Edited: jessupj
on 24 Jun 2020
your problem is related to floating point errors:
d=abs(A-b)
norm(d(4)-d(5))
3.46944695195361e-18
that's why it's only returning 1 value; one point is actually closer than another after machine precision arithmetic.
you'd need e.g. KSSV's answer below along with a tolerance for how many of the sorted differences are 'close enough'
you can also do something like:
[row,col ] = find( abs(difference-val)<2*eps )
where eps is matlab's built in machine threshold
Accepted Answer
KSSV
on 24 Jun 2020
Edited: KSSV
on 24 Jun 2020
d = abs(A-b) ;
[d,idx] = sort(d) ; % sort them in increasing order
iwant = min(A(idx(1:2)))
You can try knnsearch...read about it.
1 Comment
Daniel Vazquez Pombo
on 24 Jun 2020
Edited: Daniel Vazquez Pombo
on 25 Jun 2020
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!