Main Content

Nearest Neighbors

Find nearest neighbors using exhaustive search or Kd-tree search

A Nearest neighbor search locates the k-nearest neighbors or all neighbors within a specified distance to query data points, based on the specified distance metric. Available distance metrics include Euclidean, Hamming, and Mahalanobis, among others.

Statistics and Machine Learning Toolbox™ offers two ways to find nearest neighbors. You can create a searcher object with a training data set, and pass the object and query data sets to the object functions (knnsearch and rangesearch). Or, you can use the knnsearch and rangesearch functions, which take both a training data set and a query data set directly. Creating a searcher object is preferable when you have multiple query data sets because the searcher object stores information common to the data sets. For example, a KDTreeSearcher object stores a Kd-tree.

Blocks

KNN SearchFind k-nearest neighbors using searcher object (Since R2023b)

Functions

expand all

ExhaustiveSearcherCreate exhaustive nearest neighbor searcher
KDTreeSearcherCreate Kd-tree nearest neighbor searcher
hnswSearcherHierarchical Navigable Small Worlds (HNSW) approximate nearest neighbor search (Since R2024a)
creatensCreate nearest neighbor searcher object

Find Neighbors Using Searcher Object

knnsearchFind k-nearest neighbors using searcher object
rangesearchFind all neighbors within specified distance using searcher object

Find Neighbors Using Input Data

knnsearchFind k-nearest neighbors using input data
rangesearchFind all neighbors within specified distance using input data

Topics