18
$\begingroup$

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?

$\endgroup$

2 Answers 2

14
$\begingroup$

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} *)
$\endgroup$
1
  • 8
    $\begingroup$ 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[...] $\endgroup$
    – Szabolcs
    May 15, 2013 at 23:07
9
$\begingroup$

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}}

$\endgroup$
2
  • $\begingroup$ Is this any different from Automatic or just an alias? Oh, nice update, I see. $\endgroup$
    – Mr.Wizard
    Jul 29, 2017 at 14:52
  • 2
    $\begingroup$ @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. $\endgroup$
    – kglr
    Jul 29, 2017 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.