# Creating a NearestFunction that returns an index

I use Nearest repeatedly for large data sets. For example

pts = RandomReal[{-1, 1}, {1000, 3}];
Nearest[pts, {0, 0, 0}]


I am interested in the index of the nearest point, so I use

ind = First@Nearest[pts -> Automatic, {0, 0, 0}]


How do I create a NearestFunction that can return an index. Returning a point is easy

nf = Nearest[pts];
nf[{0, 0, 0}]


but there is seemingly no option to return the index?

## 2 Answers

From documentation:

Nearest[{elem₁ -> v₁, elem₂ -> v₂, …}, x] gives the vᵢ corresponding to the elemᵢ to which x is nearest.

Nearest[data] generates a NearestFunction[…] that can be applied repeatedly to different x."

We can use these two points as below.

pts = RandomReal[{-1, 1}, {1000, 3}];
nf = Nearest[Thread[pts -> Range[Length[pts]]]];

In[380]:= nf[{0, 0, 0}]

(* Out[380]= {973} *)

In[381]:= pts[[973]]

(* Out[381]= {0.0842448696868, 0.00699056059919, -0.0130070656885} *)

• Or just use Automatic, as in the question. This seems to work: Nearest[RandomReal[1, 10] -> Automatic]. It saves the Thread and the Range@Length[...] May 15, 2013 at 23:07

In version 11, you can also use pts -> "Index":

SeedRandom[1]
pts = RandomReal[{-1, 1}, {1000, 3}];
nF  = Nearest[pts -> "Index"];
nF[{0,0,0}]


{264}

You can have a NearestFunction returning multiple properties:

nF2 = Nearest[pts -> {"Index", "Element","Distance"}];
nF2[{0,0,0}]


{{264, {0.0284666, -0.0158014, -0.100454}, 0.105599}}

• Is this any different from Automatic or just an alias? Oh, nice update, I see. Jul 29, 2017 at 14:52
• @Mr.Wizard, it seems it is not just an alias. For example, Nearest[pts->{Automatic, "Element","Distance"}] doesn't work but Nearest[pts->{"Index", "Element","Distance"}] does.
– kglr
Jul 29, 2017 at 14:55