Efficiently searching a list for the position of the closest number to a specified number
SeedRandom[42];
haystack = RandomReal[1, 6300];
AbsoluteTiming[
f = Nearest[haystack -> Range@Length@haystack];
{f[.3, 1], haystack[[f[.3, 1]]]}]
(*
-> {0.015625, {{3123}, {0.300033}}}
*)
Of course in this case most of the time is expended calculating the nearest function. If your points aren't changing from one use to the next, the time for calculating f[}
is nil for 6K points.
The second argument of f[]
specifies that Nearest[]
should return only one point
In versions 10+, you can have a NearestFunction
that returns multiple properties, such as the "Index"
of the nearest element and the "Element"
itself:
SeedRandom[42];
haystack = RandomReal[1, 1000000];
f = Nearest[haystack ->{"Index", "Element"}];
AbsoluteTiming[f[.312345]]
{0.000072, {{101999, 0.312345}}}