Using Nearest

(RefLink[Nearest, paclet:ref/Nearest]) is used to find elements in a list that are closest to a given data point.

(RefLink[Nearest, paclet:ref/Nearest]) function.

(RefLink[Nearest, paclet:ref/Nearest]) works with numeric lists, tensors, or a list of strings.

This finds the elements nearest to 4.5:

Nearest[{1,2,3,4,5,6,7,8},4.5]

This finds 3 elements nearest to 4.5:

Nearest[{1,2,3,4,5,6,7,8},4.5,3]

This finds all elements nearest to 4.5 within a radius of 2:

Nearest[{1,2,3,4,5,6,7,8},4.5,{Infinity, 2}]

This finds the points nearest to {1,2} in 2D:

Nearest[{{1,1},{2,2},{3,3}},{1,2}]

This finds the nearest string to "cat":

Nearest[{"bat","sad","cake"},"cat"]

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

Here two-dimensional points are labeled:

Nearest[{{1,1}->a,{2,2}->b,{3,3}->c},{1,2}]

Nearest[{{1,1},{2,2},{3,3}}->{a,b,c},{1,2}]

This labels the elements using successive integers:

Nearest[{{1,1},{2,2},{3,3},{4,5},{7,7}}-> Automatic,{4,4}]

If (RefLink[Nearest, paclet:ref/Nearest]) is to be applied repeatedly to the same numerical data, you can get significant performance gains by first generating a (RefLink[NearestFunction, paclet:ref/NearestFunction]).

This generates a set of 10,000 points in 2D and a (RefLink[NearestFunction, paclet:ref/NearestFunction]):

pts = RandomReal[1,{10000,2}];
nf=Nearest[pts]

This finds points in the set that are closest to the 10 target points:

target = RandomReal[1,{10,2}];
res=Map[nf,target];//Timing

It takes much longer if (RefLink[NearestFunction, paclet:ref/NearestFunction]) is not used:

res2=Map[Nearest[pts,#]&,target];//Timing

res==res2

Option for (RefLink[Nearest, paclet:ref/Nearest]).

For numerical data, by default (RefLink[Nearest, paclet:ref/Nearest]) uses the (RefLink[EuclideanDistance, paclet:ref/EuclideanDistance]). For strings, (RefLink[EditDistance, paclet:ref/EditDistance]) is used.