# Using Nearest

Nearest is used to find elements in a list that are closest to a given data point.

 Nearest[{elem1,elem2,…},x] give the list of elemi to which x is nearest Nearest[{elem1->v1,elem2->v2,…},x] give the vi corresponding to the elemi to which x is nearest Nearest[{elem1,elem2,…}->{v1,v2,…},x] give the same result Nearest[{elem1,elem2,…}->Automatic,x] take the vi to be the integers 1, 2, 3, … Nearest[data,x,n] give the n nearest elements to x Nearest[data,x,{n,r}] give up to the n nearest elements to x within a radius r Nearest[data] generate a which can be applied repeatedly to different x

Nearest function.

Nearest works with numeric lists, tensors, or a list of strings.

This finds the elements nearest to 4.5.
 In[1]:=
 Out[1]=
This finds 3 elements nearest to 4.5.
 In[2]:=
 Out[2]=
This finds all elements nearest to 4.5 within a radius of 2.
 In[3]:=
 Out[3]=
This finds the points nearest to {1,2} in 2D.
 In[4]:=
 Out[4]=
This finds the nearest string to "cat".
 In[5]:=
 Out[5]=

The rule-based data syntax lets you use nearest elements to return their labels.

Here two-dimensional points are labeled.
 In[6]:=
 Out[6]=
 In[7]:=
 Out[7]=
This labels the elements using successive integers.
 In[8]:=
 Out[8]=

If Nearest is to be applied repeatedly to the same numerical data, you can get significant performance gains by first generating a NearestFunction.

This generates a set of 10,000 points in 2D and a NearestFunction.
 In[9]:=
 Out[9]=
This finds points in the set that are closest to the 10 target points.
 In[10]:=
 Out[10]=
It takes much longer if NearestFunction is not used.
 In[11]:=
 Out[11]=
 In[12]:=
 Out[12]=
 option name default value DistanceFunction Automatic the distance metric to use

Option for Nearest.

For numerical data, by default Nearest uses the EuclideanDistance. For strings, EditDistance is used.