MATHEMATICA TUTORIAL

# 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.
 Out[1]=
This finds 3 elements nearest to 4.5.
 Out[2]=
This finds all elements nearest to 4.5 within a radius of 2.
 Out[3]=
This finds the points nearest to in 2D.
 Out[4]=
This finds the nearest string to "cat".
 Out[5]=

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

Here two-dimensional points are labeled.
 Out[6]=
 Out[7]=
This labels the elements using successive integers.
 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.
 Out[9]=
This finds points in the set that are closest to the 10 target points.
 Out[10]=
It takes much longer if NearestFunction is not used.
 Out[11]=
 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.

## Tutorial CollectionTutorial Collection

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