indmin(abs(x-val)) is easy and pretty good, but it does create two
temporaries. Faster would be
function closest_index(x, val)
ibest = start(eachindex(x))
dxbest = abs(x[ibest]-val)
for I in eachindex(x)
dx = abs(x[I]-val)
if dx < dxbest
dxbest = dx
ibest = I
end
end
ibest
end
This should not allocate any memory and is likely the fastest. (It might be
slightly faster with @inbounds, of course...)
It would be possible to create an indmin(f, x) that applies f to each element
of x and returns the index of the minimum; this would be efficient in the
development version of julia but not julia-0.4.
Best,
--Tim
On Sunday, April 10, 2016 04:40:07 AM Fred wrote:
> Hi,
>
> I am looking for the most efficient (fastest) way to find the indice of the
> element with the nearest value of a float in an array.
>
> x = [1:0.1:10]
>
> julia> x
> 91-element Array{Float64,1}:
> 1.0
> 1.1
> 1.2
> 1.3
> 1.4
> ⋮
> 9.4
> 9.5
> 9.6
> 9.7
> 9.8
> 9.9
> 10.0
>
> It is very easy to find the indice of an exact value of x, for example 8.2
>
> julia> find(x .== 8.2)
> 1-element Array{Int64,1}:
> 73
>
> But if I want the indice of the closest value of 8.22
>
> julia> minimum(abs(x-8.22))
> 0.02000000000000135
>
> julia> find(x .== minimum(abs(x-8.22)))
> 0-element Array{Int64,1}
>
>
> Of course it is easy to do that with a loop but is it the fastest solution ?
>
> min_i = 0
> min_x = 1.0
>
> for i=[1:length(x)]
> e = abs(collect(x)[i] - 8.22)
> if e < min_x
> min_x = e
> min_i = i
> end
> end
>
> println(min_x, " -> ", min_i)
> 0.02000000000000135 -> 73
>
>
> Thanks for your comments !