Nearest

Nearest[{elem1, elem2, ...}, x]
gives the list of to which x is nearest.

Nearest[{elem1->v1, elem2->v2, ...}, x]
gives the corresponding to the to which x is nearest.

Nearest[{elem1, elem2, ...}->{v1, v2, ...}, x]
gives the same result.

Nearest[{elem1, elem2, ...}->Automatic, x]
takes the to be successive integers i.

Nearest[data, x, n]
gives the n nearest to x.

Nearest[data]
generates a NearestFunction[...] that can be applied repeatedly to different x.

Details and OptionsDetails and Options

  • If the are vectors or matrices of numbers, Nearest by default in effect uses the metric Norm[#1-#2]&.
  • For strings, Nearest by default uses the edit distance metric.
  • The following option can be given:
  • DistanceFunctionAutomaticthe distance metric to use
  • For images, Nearest[{img1, img2, ...}, img, DistanceFunction->f] effectively uses DistanceFunction->(ImageDistance[#1, #2, DistanceFunction->f]&).
  • When several elements are returned, the nearest ones are given first.
  • If several elements are at the same distance, they are returned in the order they appear in data.

ExamplesExamplesopen allclose all

Basic Examples (4)Basic Examples (4)

Find the element nearest to 20:

In[1]:=
Click for copyable input
Out[1]=

Find the 3 elements nearest to 20:

In[2]:=
Click for copyable input
Out[2]=

Find which element is nearest to in 2D:

In[1]:=
Click for copyable input
Out[1]=

Find "nearest" strings:

In[1]:=
Click for copyable input
Out[1]=
In[2]:=
Click for copyable input
Out[2]=

Find the nearest image partition to a subimage:

In[1]:=
Click for copyable input
In[2]:=
Click for copyable input
Out[2]=
New in 6 | Last modified in 9
New to Mathematica? Find your learning path »
Have a question? Ask support »