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 to which x is nearest
Nearest[{elem1->v1,elem2->v2,...},x]
give the corresponding to the to which x is nearest
Nearest[{elem1,elem2,...}->{v1,v2,...},x]
give the same result
Nearest[{elem1,elem2,...}->Automatic,x]
take the 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 NearestFunction[...] 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]:=
Click for copyable input
Out[1]=
This finds 3 elements nearest to 4.5.
In[2]:=
Click for copyable input
Out[2]=
This finds all elements nearest to 4.5 within a radius of 2.
In[3]:=
Click for copyable input
Out[3]=
This finds the points nearest to in 2D.
In[4]:=
Click for copyable input
Out[4]=
This finds the nearest string to "cat".
In[5]:=
Click for copyable input
Out[5]=

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

Here two-dimensional points are labeled.
In[6]:=
Click for copyable input
Out[6]=
In[7]:=
Click for copyable input
Out[7]=
This labels the elements using successive integers.
In[8]:=
Click for copyable input
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]:=
Click for copyable input
Out[9]=
This finds points in the set that are closest to the 10 target points.
In[10]:=
Click for copyable input
Out[10]=
It takes much longer if NearestFunction is not used.
In[11]:=
Click for copyable input
Out[11]=
In[12]:=
Click for copyable input
Out[12]=
option name
default value
DistanceFunctionAutomaticthe distance metric to use

Option for Nearest.

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

New to Mathematica? Find your learning path »
Have a question? Ask support »