Note: This page has been translated by MathWorks. Click here to see

To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Find *k*-nearest neighbors using data

`Idx = knnsearch(X,Y)`

`Idx = knnsearch(X,Y,Name,Value)`

`[Idx,D] = knnsearch(___)`

returns `Idx`

= knnsearch(`X`

,`Y`

,`Name,Value`

)`Idx`

with additional options specified using one or more
name-value pair arguments. For example, you can specify the number of nearest
neighbors to search for and the distance metric used in the search.

For a fixed positive integer

*k*,`knnsearch`

finds the*k*points in`X`

that are the nearest to each point in`Y`

. To find all points in`X`

within a fixed distance of each point in`Y`

, use`rangesearch`

.`knnsearch`

does not save a search object. To create a search object, use`createns`

.

For information on a specific search algorithm, see Distance Metrics.

If you set the `knnsearch`

function's `'NSMethod'`

name-value pair argument to the appropriate value (`'exhaustive'`

for
an exhaustive search algorithm or `'kdtree'`

for a
*K*d-tree algorithm), then the search results are equivalent to the
results obtained by conducting a distance search using the `knnsearch`

object function. Unlike the `knnsearch`

function, the `knnsearch`

object function requires an
`ExhaustiveSearcher`

or a `KDTreeSearcher`

model object.

[1] Friedman, J. H., J. Bentely, and R. A. Finkel. “An Algorithm for Finding
Best Matches in Logarithmic Expected Time.” *ACM Transactions on
Mathematical Software* 3, no. 3 (1977): 209–226.