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 !