Borrar filtros
Borrar filtros

How to find the index of the closest value to some number in 1D array ?

1.127 visualizaciones (últimos 30 días)
How to find the index in 1D array that has closest value to some number ?
val =-1.03
val1 = 1.04
x = -10:0.009:10
ind1 = find (A==val) % will work if the val is exact match
  2 comentarios
Jose
Jose el 15 de Feb. de 2023
Editada: Jose el 15 de Feb. de 2023
Index=find(min(abs(Array-target))==abs(Array-target))
that should work even if the # of sig digits change in your array. It finds the location of value in the array, that when substracted from your target value has the smallest difference (i.e. closest match).
Din N
Din N el 17 de Mzo. de 2023
This does give the closest value, but if you want the closest value to be smaller than your target value? For example if my target value is 7300, how can I specify here that I only want the index for the closest value that is smaller than 7300?

Iniciar sesión para comentar.

Respuesta aceptada

per isakson
per isakson el 27 de Mzo. de 2015
Editada: per isakson el 2 de Abr. de 2019
Hint:
>> [ d, ix ] = min( abs( x-val ) );
>> x(ix-1:ix+1)
ans =
-1.0360 -1.0270 -1.0180
ix is the "index in 1D array that has closest value to" val
"if the val is exact match"   that's tricky with floating point numbers
  2 comentarios
Peter Kövesdi
Peter Kövesdi el 2 de Abr. de 2019
Take care: This routine fails with uint data types. Transform them to double first:
double(x);
or
double(val);
as needed.

Iniciar sesión para comentar.

Más respuestas (3)

Peter Kövesdi
Peter Kövesdi el 1 de Abr. de 2019
ind = interp1(x,1:length(x),val,'nearest');
also does it.
But a short comparison shows disadvantages in timing:
f1=@()interp1(x,1:length(x),val,'nearest');
f2=@()min( abs( x-val ) );
timeit(f1)>timeit(f2)
  1 comentario
Andoni Medina Murua
Andoni Medina Murua el 18 de Ag. de 2022
Editada: Andoni Medina Murua el 18 de Ag. de 2022
However
interp1(x,1:length(x),val,'nearest');
works in case val is an array, which doesn't happen with
min( abs( x-val ) );

Iniciar sesión para comentar.


Revant Adlakha
Revant Adlakha el 26 de Feb. de 2021
You could also use something like this, where f(x) is the function and x is the value of interest.
ind = find(min(abs(f(x) - x)) == abs(f(x) - x));

Ernest Nachaki
Ernest Nachaki el 27 de Mayo de 2022
Try this
index = fix(interp1(array,find(array),value));

Categorías

Más información sobre Matrix Indexing 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