How to select the first appearance of the minimum value?

4 visualizaciones (últimos 30 días)
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 comentarios
jessupj
jessupj el 24 de Jun. de 2020
Editada: jessupj el 24 de Jun. de 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
Daniel Vazquez Pombo el 24 de Jun. de 2020
Thank you for the explanation, I will remember it in the future

Iniciar sesión para comentar.

Respuesta aceptada

KSSV
KSSV el 24 de Jun. de 2020
Editada: KSSV el 24 de Jun. de 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 comentario
Daniel Vazquez Pombo
Daniel Vazquez Pombo el 24 de Jun. de 2020
Editada: Daniel Vazquez Pombo el 25 de Jun. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Data Type Identification en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by