Fred

Yes, the fastest way is a loop. (It might be possible to extend e.g.
`minimum` by a "predicate" argument, but that would require a change
to the base library.)

You would write the loop slightly differently, though:
```Julia
mini = 0
minx = 0.0
mindx = typemax(Float64)
for (i,x) in enumerate(array)
    dx = abs(x - x0)
    if dx < mindx
        mini, minx, mindx = i, x, dx
    end
end
mini, minx, mindx
```

This will return `imin=0` for empty inputs.

-erik



On Sun, Apr 10, 2016 at 7:40 AM, Fred <[email protected]> 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 !
>



-- 
Erik Schnetter <[email protected]>
http://www.perimeterinstitute.ca/personal/eschnetter/

Reply via email to