How to speed up this code?

1 visualización (últimos 30 días)
K E
K E el 13 de Nov. de 2014
Comentada: K E el 14 de Nov. de 2014
I would like fast code to find the index of the closest element of a vector to a scalar. Here's what I am doing now,
someVector = [1 3.5 5 7 9];
someScalar = 4;
iClosest = find(abs(someVector - someScalar) == min(abs(someVector - someScalar)));
The returned index is 2 since the 2nd element is closest to 4. A parent program spends a lot of time on this line according to the profiler. I'd like to know if it can be done faster or if there's a built-in solution.

Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 13 de Nov. de 2014
[~,idx]=min(abs(someVector - someScalar))
  1 comentario
K E
K E el 14 de Nov. de 2014
Thanks, knew there was a more elegant way.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by