Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

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} *)
share|improve this answer
3  
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[...] –  Szabolcs May 15 '13 at 23:07
    
Thanks! It works well. –  JMann May 15 '13 at 23:19
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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