- See Also
-
Related Guides
- Logic & Boolean Algebra
- Boolean Computation
- Computational Geometry
- Supervised Machine Learning
- Text Analysis
- Natural Language Processing
- Sequence Alignment & Comparison
- Distance and Similarity Measures
- Date & Time
- Machine Learning
- Scientific Models
- Linguistic Data
- Math & Counting Operations on Lists
- Computer Vision
- Audio Analysis
- Audio Processing
- Speech Computation
- Tech Notes
-
- See Also
-
Related Guides
- Logic & Boolean Algebra
- Boolean Computation
- Computational Geometry
- Supervised Machine Learning
- Text Analysis
- Natural Language Processing
- Sequence Alignment & Comparison
- Distance and Similarity Measures
- Date & Time
- Machine Learning
- Scientific Models
- Linguistic Data
- Math & Counting Operations on Lists
- Computer Vision
- Audio Analysis
- Audio Processing
- Speech Computation
- Tech Notes
Nearest[{elem1,elem2,…},x]
gives the list of elemi to which x is nearest.
Nearest[{elem1v1,elem2v2,…},x]
gives the vi corresponding to the elemi to which x is nearest.
Nearest[{elem1,elem2,…}{v1,v2,…},x]
gives the same result.
Nearest[{elem1,elem2,…}prop,x]
gives the property prop for the elemi to which x is nearest.
Nearest[data,{x1,x2,…}]
effectively gives {Nearest[data,x1],Nearest[data,x2],…}.
Nearest[data,x,n]
gives the n nearest elemi to x.
Nearest[data,x,{n,r}]
gives the n or fewer nearest elemi to x that are within radius r of x.
Nearest[data]
generates a NearestFunction[…] that can be applied repeatedly to different x.
Nearest
Nearest[{elem1,elem2,…},x]
gives the list of elemi to which x is nearest.
Nearest[{elem1v1,elem2v2,…},x]
gives the vi corresponding to the elemi to which x is nearest.
Nearest[{elem1,elem2,…}{v1,v2,…},x]
gives the same result.
Nearest[{elem1,elem2,…}prop,x]
gives the property prop for the elemi to which x is nearest.
Nearest[data,{x1,x2,…}]
effectively gives {Nearest[data,x1],Nearest[data,x2],…}.
Nearest[data,x,n]
gives the n nearest elemi to x.
Nearest[data,x,{n,r}]
gives the n or fewer nearest elemi to x that are within radius r of x.
Nearest[data]
generates a NearestFunction[…] that can be applied repeatedly to different x.
Details and Options
- Nearest works for a variety of data, including numerical, geospatial, textual, and visual, as well as dates and times.
- The data can also be given as an association. In this case, Nearest[<|key1val1,key2val2,…|>] is equivalent to Nearest[{val1key1,val2key2,…}].
- In Nearest[{elem1,elem2,…}prop,…], possible forms for prop include:
-
"Element" the elemi found to be nearest "Index" the index i of the elemi found to be nearest "Distance" the distance to the nearest elemi {prop1,prop2,…} a list of multiple forms All an association giving element, index and distance - When Nearest returns several elements elemi, the nearest ones are given first.
- If several elements are at the same distance, they are returned in the order they appear in data.
- Nearest[data,x,{All,r}] can be used to get all elemi within radius r.
- The following options can be given:
-
DistanceFunction Automatic the distance metric to use Method Automatic method to use WorkingPrecision Automatic precision to use for numeric data - By default, the following distance functions are used for different types of elemi:
-
Norm[#1-#2]& numeric data JaccardDissimilarity Boolean data EditDistance strings ColorDistance colors ImageDistance images DateDifference dates and times GeoDistance geospatial data - Nearest with geospatial data uses GeoDistance to compute distances. The data can be given as a list of GeoPosition objects, or a GeoPosition containing an array of points.
- For images or colors and a distance function f, DistanceFunction->f is passed to ImageDistance and ColorDistance, respectively. »
- All images are conformed using ConformImages. With DistanceFunction->Automatic, dimensionality reduction based on discrete cosine transform is applied to the set of images.
- Using Norm[#1-#2,p]& for
or named distance functions such as ManhattanDistance, ChessboardDistance, and EuclideanDistance can invoke special optimizations for numeric vector data. - Possible settings for Method include "Octree", "KDtree", and "Scan".
- Possible settings for the WorkingPrecision option are:
-
MachinePrecision use machine-precision numbers p use precision p Automatic use adaptive precision to resolve nearest points
Examples
open all close allBasic Examples (5)
Find the element nearest to 20:
Nearest[{1, 2, 4, 8, 16, 32}, 20]Find the 3 elements nearest to 20:
Nearest[{1, 2, 4, 8, 16, 32}, 20, 3]Find which element is nearest to {2,3} in 2D:
Nearest[{{-1, -1}, {1, -1}, {1, 1}, {-1, 1}}, {2, 3}]Nearest[{"aaaa", "abaa", "bbbb", "aaaba"}, "aaba", 3]EditDistance[#, "aaba"]& /@ {"aaaa", "abaa", "bbbb", "aaaba"}l = {RGBColor[1., 0.7573220867762727, 0.8225376261211264], RGBColor[1., 0.9053403248427643, 0.21717287340883917], RGBColor[1., 0.5544801460824762, 0.12056345655596812], RGBColor[1., 0.2818404077149421, 0.1073945311994069], RGBColor[1., 0.12423838985259317, 0.19023691956664956], RGBColor[0.8, 0.4542154246540884, 0.31688034954543], RGBColor[0.8, 0.5483770742736782, 0.16977938137471082], RGBColor[0.8, 0.03163746197875539, 0.5781619271042624], RGBColor[0.8, 0.1612089376881538, 0.15737556414394493], RGBColor[0.8, 0.947661405438111, 0.8404962405438101], RGBColor[0.5, 0.8592283961197744, 0.04768022523989446], RGBColor[0.5, 0.04821552495323611, 0.9686564512239644], RGBColor[0.5, 0.5966778129134023, 0.8001648440588174], RGBColor[0.5, 0.5307402622478448, 0.7029200788120107], RGBColor[0.5, 0.6654316628707297, 0.9850955091132039]};Nearest[l, Red, 3]Find the nearest image partition to a subimage:
i = [image];subimage = [image];Nearest[Flatten@ImagePartition[i, 45], subimage]Scope (9)
Nearest[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5, 3]Give the elements within radius 2:
Nearest[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5, {All, 2}]Give at most 3 nearest elements within radius 2:
Nearest[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5, {3, 2}]Nearest[Table[PauliMatrix[i], {i, 3}], {{1, -2}, {3, -4}}]Find which element is nearest to {2,3} in 2D and return the appropriate label:
Nearest[{{-1, -1} -> a, {1, -1} -> b, {1, 1} -> c, {-1, 1} -> d}, {2, 3}]Compute the same using an Association:
Nearest[<|a -> {-1, -1}, b -> {1, -1}, c -> {1, 1}, d -> {-1, 1}|>, {2, 3}]Return the index for the nearest string:
Nearest[{"I'm", "sorry", "Dave"} -> "Index", "David"]Return an Association giving the string element, index, and distance:
Nearest[{"I'm", "sorry", "Dave"} -> All, "David"]Find the 3 elements nearest to 20, simultaneously reporting the elements and their distance to 20:
Nearest[{1, 2, 4, 8, 16, 32} -> {"Element", "Distance"}, 20, 3]For uniform random points in 3D, give the distances for the 10 nearest to the origin:
points = RandomReal[{-1, 1}, {10000, 3}];
Nearest[points -> "Distance", {0, 0, 0}, 10]For each of the 10 nearest, give an Association including the point element, index and distance:
Nearest[points -> All, {0, 0, 0}, 10] // TableFormCreate a lookup function for future use:
nf = Nearest[{{-1, -1, 0} -> a, {1, -1, 1} -> b, {1, 1, 0} -> c, {-1, 1, 0} -> d}]nf[{2, 0, 0}]Find the date nearest to a given DateObject:
dates = {DateObject[{2022, 3, 8, 2, 0, 0.}, "Instant", "Gregorian", -5.], DateObject[{2022, 5, 29, 9, 6, 7.64248}, "Instant", "Gregorian", -4.], DateObject[{2022, 8, 4, 18, 26, 14.}, "Instant", "Gregorian", 0.], DateObject[{2023, 1, 5, 20, 45, 19.2}, "Instant", "Gregorian", 2.]};Nearest[dates, Now]Nearest[{DateObject[{1500}, "Year", "Gregorian", -6.], DateObject[{1550}, "Year", "Gregorian", -6.], DateObject[{1600}, "Year", "Gregorian", -6.], DateObject[{1650}, "Year", "Gregorian", -6.]}, EntityValue[["galleleo"], "BirthDate"]]Find out which of these {lat,lon} points on Earth is closest to you:
points = GeoPosition[{{0, 0}, {0, 90}, {0, 180}, {0, -90}, {90, 0}, {-90, 0}}]HereNearest[points, Here]Express the input as a list of separate GeoPosition objects instead:
Thread[points]Nearest[%, Here]Report simultaneously the closest point and the distance to it:
Nearest[points -> {"Element", "Distance"}, Here]Options (6)
DistanceFunction (3)
By default, normal Euclidean distance is used for points:
Nearest[{{1.5, .6}, {2, 0}, {1.25, 1.25}}, {0, 0}]Use the ManhattanDistance, which sums the length of each side:
Nearest[{{1.5, .6}, {2, 0}, {1.25, 1.25}}, {0, 0}, DistanceFunction -> ManhattanDistance]The ChessboardDistance only takes into account the dimension with the largest separation:
Nearest[{{1.5, .6}, {2, 0}, {1.25, 1.25}}, {0, 0}, DistanceFunction -> ChessboardDistance]The DistanceFunction can be given as a symbol:
dist[{u_, v_}, {x_, y_}] := 3Abs[u - x] + 2Abs[v - y]Nearest[{{1.5, .6}, {2, 0}, {1.25, 1.25}}, {0, 0}, DistanceFunction -> dist]Nearest[{{1.5, .6}, {2, 0}, {1.25, 1.25}}, {0, 0}, DistanceFunction -> (3Abs[#1[[1]] - #2[[1]]] + 2Abs[#1[[2]] - #2[[2]]]&)]Find nearest colors using a color distance different from the default distance in ColorDistance:
l = {RGBColor[1., 0.7573220867762727, 0.8225376261211264], RGBColor[1., 0.9053403248427643, 0.21717287340883917], RGBColor[1., 0.5544801460824762, 0.12056345655596812], RGBColor[1., 0.2818404077149421, 0.1073945311994069], RGBColor[1., 0.12423838985259317, 0.19023691956664956], RGBColor[0.8, 0.4542154246540884, 0.31688034954543], RGBColor[0.8, 0.5483770742736782, 0.16977938137471082], RGBColor[0.8, 0.03163746197875539, 0.5781619271042624], RGBColor[0.8, 0.1612089376881538, 0.15737556414394493], RGBColor[0.8, 0.947661405438111, 0.8404962405438101], RGBColor[0.5, 0.8592283961197744, 0.04768022523989446], RGBColor[0.5, 0.04821552495323611, 0.9686564512239644], RGBColor[0.5, 0.5966778129134023, 0.8001648440588174], RGBColor[0.5, 0.5307402622478448, 0.7029200788120107], RGBColor[0.5, 0.6654316628707297, 0.9850955091132039]};Nearest[l, Red, 3, DistanceFunction -> "CIE2000"]Method (2)
Compare different methods for machine-precision data:
methods = {Automatic, "Scan", "KDtree", "Octree"};In three dimensions, the "KDtree" method is faster:
data3 = RandomReal[1, {10 ^ 6, 3}];
test3 = RandomReal[1, {10 ^ 3, 3}];TableForm[Table[{
First[AbsoluteTiming[nf3 = Nearest[data3, Method -> m];]],
First[AbsoluteTiming[nf3[test3];]],
First[AbsoluteTiming[nf3[test3, 25];]]}, {m, methods}], TableHeadings -> {methods, {"Setup", "1 nearest", "25 nearest"}}]In 20 dimensions, a simple scan is faster:
methods = {Automatic, "Scan", "KDtree"};data20 = RandomReal[1, {10 ^ 5, 20}];
test20 = RandomReal[1, {10 ^ 3, 20}];TableForm[Table[{
First[AbsoluteTiming[nf20 = Nearest[data20, Method -> m];]],
First[AbsoluteTiming[nf20[test20];]],
First[AbsoluteTiming[nf20[test20, 25];]]}, {m, methods}], TableHeadings -> {methods, {"Setup", "1 nearest", "25 nearest"}}]The setting Method->{"KDtree","LeafSize"->s} may be used to control the maximum number of points in any leaf of the KD tree constructed:
data = RandomReal[1, {10 ^ 6, 3}];
test = RandomReal[1, {10 ^ 4, 3}];times = Table[{s, First[AbsoluteTiming[nf = Nearest[data, Method -> {"KDtree", "LeafSize" -> s}];]], First[AbsoluteTiming[nf[test];]]}, {s, 50}];ListPlot[times[[All, {1, 2}]]]Plot the lookup time for
different points:
ListPlot[times[[All, {1, 3}]]]WorkingPrecision (1)
Using WorkingPrecision->MachinePrecision ensures the fastest evaluation method is used:
data = Pi + RandomInteger[{-9, 9}, {321, 4}];
test = E + RandomInteger[{-9, 9}, {23, 4}];First[AbsoluteTiming[Nearest[data, test]]]First[AbsoluteTiming[Nearest[data, test, WorkingPrecision -> MachinePrecision]]]The results may not be correct if the numbers are not all distinct to machine precision:
data = 10 ^ 20 + RandomInteger[{-9, 9}, {321, 4}];
test = 10 ^ 20 + RandomInteger[{-9, 9}, {23, 4}];First[AbsoluteTiming[na = Nearest[data -> Automatic, test]]]First[AbsoluteTiming[nmp = Nearest[data -> Automatic, test, WorkingPrecision -> MachinePrecision]]]nmp === naAll the points are effectively the same to machine precision:
Dimensions[nmp]An appropriate higher value of precision will work:
First[AbsoluteTiming[np = Nearest[data -> Automatic, test, WorkingPrecision -> 24]]]na === npApplications (8)
Plot the Nearest of a list of:
Plot[First[Nearest[{1, 3, 4, 7, 8}, x]], {x, 0, 10}]nf = Nearest[Table[{t Sin[t], t Cos[t]} -> t, {t, 5}]]DensityPlot[First[nf[{x, y}]], {x, -5, 5}, {y, -5, 5}]DensityPlot[First[nf[{x, y}]], {x, -5, 5}, {y, -5, 5}, PlotPoints -> 50]Use a 1-norm ("taxicab distance"):
nf = Nearest[Table[{t Sin[t], t Cos[t]} -> t, {t, 5}], DistanceFunction -> (Norm[#1 - #2, 1]&)];DensityPlot[First[nf[{x, y}]], {x, -5, 5}, {y, -5, 5}, PlotPoints -> 50, Epilog -> {Red, Point[Table[{t Sin[t], t Cos[t]}, {t, 5}]]}]Highlight the 200 random points closest to the origin:
With[{data = RandomReal[{-1, 1}, {1000, 2}]}, ListPlot[{data, Nearest[data, {0, 0}, 200]}, PlotStyle -> {Blue, Red}]]With[{data = RandomReal[{-1, 1}, {1000, 2}]}, ListPlot[{data, Nearest[data, {0, 0}, 200, DistanceFunction -> (Norm[#1 - #2, 1]&)]}, PlotStyle -> {Blue, Red}]]Create a nearest function from all the words in a dictionary:
nf = Nearest[DictionaryLookup[]]Look up words closest to a given word:
nf["pickel"]nf["pickel", 10]Find the outputs from running a sequence of elementary cellular automata:
Table[First[CellularAutomaton[i, {{1}, 0}, {{3}, All}]] -> i, {i, 0, 4}]Generate a complete list of outputs from all 256 elementary cellular automata:
ca = Table[First[CellularAutomaton[i, {{1}, 0}, {{5}, All}]] -> i, {i, 0, 255}];Find which rules give outputs nearest the specified sequences:
Nearest[ca, {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}]Nearest[ca, {1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1}]Use a negative distance function to find the element farthest away from the given element:
Nearest[{1, 2, 3, 4, 5}, 1, DistanceFunction -> (-Abs[#1 - #2]&)]Nearest[{1, 2, 3, 4, 5}, 5, DistanceFunction -> (-Abs[#1 - #2]&)]Show the returned element for all values between 1 and 5:
Plot[Nearest[{1, 2, 3, 4, 5}, x, DistanceFunction -> (-Abs[#1 - #2]&)], {x, 1, 5}]polygon = EntityValue[["Mexico"], "Polygon"]Compute the nearest of the points of that polygon from your current geo location:
nearest = Nearest[polygon[[1]], Here]Draw the geodesic from your location to that point:
GeoGraphics[{Arrow[GeoPath[{Here, nearest[[1]]}]], EdgeForm[Black], polygon}]Properties & Relations (2)
In the case of a tie, all nearest elements are returned in order:
Nearest[{5, 1, 13, 9, 16}, 3]The single argument form of Nearest returns a NearestFunction object:
data = RandomReal[1, {10000}];
nf = Nearest[data]This is an optimized lookup function, which is faster than calling Nearest repeatedly:
Do[nf[RandomReal[]], {500}] // AbsoluteTimingDo[Nearest[data, RandomReal[]], {500}] // AbsoluteTimingNeat Examples (1)
See Also
GeoNearest RegionNearest FeatureNearest NearestTo NearestNeighborGraph NearestModel DistanceMatrix Predict Classify FindClusters Norm Sort Quantile Interpolation NearestFunction DistanceTransform
Function Repository: TaxonomicNearest NearestColorName MoleculeFingerprintSimilarity BinarySearch
Tech Notes
Related Guides
-
▪
- Logic & Boolean Algebra ▪
- Boolean Computation ▪
- Computational Geometry ▪
- Supervised Machine Learning ▪
- Text Analysis ▪
- Natural Language Processing ▪
- Sequence Alignment & Comparison ▪
- Distance and Similarity Measures ▪
- Date & Time ▪
- Machine Learning ▪
- Scientific Models ▪
- Linguistic Data ▪
- Math & Counting Operations on Lists ▪
- Computer Vision ▪
- Audio Analysis ▪
- Audio Processing ▪
- Speech Computation
History
Introduced in 2007 (6.0) | Updated in 2014 (10.0) ▪ 2016 (11.0) ▪ 2017 (11.1)
Text
Wolfram Research (2007), Nearest, Wolfram Language function, https://reference.wolfram.com/language/ref/Nearest.html (updated 2017).
CMS
Wolfram Language. 2007. "Nearest." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2017. https://reference.wolfram.com/language/ref/Nearest.html.
APA
Wolfram Language. (2007). Nearest. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Nearest.html
BibTeX
@misc{reference.wolfram_2026_nearest, author="Wolfram Research", title="{Nearest}", year="2017", howpublished="\url{https://reference.wolfram.com/language/ref/Nearest.html}", note=[Accessed: 13-June-2026]}
BibLaTeX
@online{reference.wolfram_2026_nearest, organization={Wolfram Research}, title={Nearest}, year={2017}, url={https://reference.wolfram.com/language/ref/Nearest.html}, note=[Accessed: 13-June-2026]}