Not sure which is faster, but here's another way to do it:
julia>
reduce((x,y)->x[2]<y[2]?x:y,(0,1000),map((x,y)->(x,abs(y-8.22)),1:length(x),x))
(73,0.02000000000000135)
- Ravi
On Sunday, April 10, 2016 at 5:10:07 PM UTC+5:30, 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 !
>
>