# How to select the first appearance of the minimum value?

1 view (last 30 days)
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.

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
Daniel Vazquez Pombo on 24 Jun 2020
Thank you for the explanation, I will remember it in the future

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)))

#### 1 Comment

Daniel Vazquez Pombo on 24 Jun 2020
thanks this solved my problem. Then if b is positive I needed to add this
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
d = abs(A-b) ;
[d,idx] = sort(d) ; % sort them in increasing order
if b<0
iwant = min(A(idx(1:2)))
else
iwant = max(A(idx(1:2)))
end
I'll leave it here in case it helps someone in the future.