*k*-nearest neighbors search using *K*d-tree
or exhaustive search

searches
for the nearest neighbor (i.e., the closest point, row, or observation)
in `Idx`

= knnsearch(`Mdl`

,`Y`

)`Mdl.X`

to each point (i.e., row or observation)
in the query data `Y`

using an exhaustive search
or a *K*d-tree. `knnsearch`

returns `Idx`

,
which is a column vector of the indices in `Mdl.X`

representing
the nearest neighbors.

returns
the indices of the closest points in `Idx`

= knnsearch(`Mdl`

,`Y`

,`Name,Value`

)`Mdl.X`

to `Y`

with
additional options specified by one or more `Name,Value`

pair
arguments. For example, specify the number of nearest neighbors to
search for, distance metric different from the one stored in `Mdl.Distance`

.
You can also specify which action to take if the closest distances
are tied.

`[`

additionally returns the matrix `Idx`

,`D`

]
= knnsearch(___)`D`

using
any of the input arguments in the previous syntaxes. `D`

contains
the distances between each observation in `Y`

that
correspond to the closest observations in `Mdl.X`

.
The function arranges the columns of `D`

in ascending
order by closeness, with respect to the distance metric.

`knnsearch`

is an object function that requires an`ExhaustiveSearcher`

or a`KDTreeSearcher`

model object and query data. Under equivalent conditions,`knnsearch`

returns the same results as`knnsearch`

when you specify the name-value pair argument`'NSMethod',`

or`'exhaustive'`

`'NSMethod',`

, respectively.`'kdtree'`

For

*k*-nearest neighbors classification, see`fitcknn`

and`ClassificationKNN`

.

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

`ClassificationKNN`

| `createns`

| `ExhaustiveSearcher`

| `fitcknn`

| `KDTreeSearcher`

| `knnsearch`

| `rangesearch`

Was this topic helpful?