RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact

Explore

  • RunMat for academia
  • RunMat vs MATLAB Online
  • Benchmarks

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

RunMat™ is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

LicensePrivacy
/
See all docs
Builtin Reference
    • bayesopt
    • classify
    • confusionmat
    • crossvalind
    • cvpartition
    • fitclinear
    • fitctree
    • fitlm
    • kmeans
    • knnsearch
    • lasso
    • lassoglm
    • linkage
    • lscov
    • mnrfit
    • optimizableVariable
    • pdist
    • pdist2
    • perfcurve
    • predict
    • regress
    • ridge
    • squareform
    • test
    • training
    • tsne

knnsearch — Find k-nearest neighbors in an observation matrix.

knnsearch(X,Y) returns one-based row indices in X for the nearest neighbors of each row in Y.

Syntax

Idx = knnsearch(X, Y)
[Idx, D] = knnsearch(X, Y, Name, Value)

Inputs

NameTypeRequiredDefaultDescription
XNumericArrayYes—Observation matrix with observations in rows.
YNumericArrayYes—Second observation matrix with observations in rows.
optionsAnyVariadic—Name-value options such as K, Distance, P, Cov, Scale, IncludeTies, NSMethod, BucketSize, CacheSize, and SortIndices.

Returns

NameTypeDescription
IdxAnyOne-based indices of nearest rows in X, or cell array of index vectors when IncludeTies is true.
DAnyDistances to nearest rows in X, or cell array of distance vectors when IncludeTies is true.

Returned values from knnsearch depend on how many outputs the caller requests.

Errors

IdentifierWhenMessage
RunMat:distance:InvalidArgumentInputs, dimensions, metrics, metric parameters, or selection options are malformed.distance helper: invalid argument
RunMat:distance:InternalRunMat cannot allocate or construct a distance output.distance helper: internal error

How knnsearch works

  • X and Y must be real numeric vectors or 2-D matrices with the same number of columns.
  • The default search is exhaustive with K=1 and Euclidean distance.
  • [Idx,D] = knnsearch(...) returns indices first and distances second. Without IncludeTies, both outputs are size(Y,1) by K numeric matrices.
  • Supported distance metrics are "euclidean", "squaredeuclidean", "cityblock", "chebychev", "minkowski", "seuclidean", "mahalanobis", "cosine", "correlation", "hamming", "jaccard", and "spearman". Fast Euclidean aliases are accepted and evaluated with the exact Euclidean implementation.
  • "P", "Scale", and "Cov" provide metric parameters for Minkowski, standardized Euclidean, and Mahalanobis distances respectively.
  • "IncludeTies",true returns size(Y,1) by 1 cell arrays whose elements contain all neighbors tied at the K-th distance. Tied outputs are sorted by distance even when "SortIndices",false is supplied.
  • "NSMethod", "BucketSize", "CacheSize", and "SortIndices" are parsed for compatibility. "NSMethod","kdtree" is accepted only for Euclidean, cityblock, Chebychev, and Minkowski distances. RunMat currently evaluates nearest neighbors exhaustively and returns sorted neighbors.
  • Typed-integer X, Y, K, BucketSize, metric parameters, and logical controls are independently gated RunMat extensions. Structural roles decode exactly; numerical distance roles must be exactly representable at the binary64 boundary.
  • MATLAB-compatible explicit gpuArray calls require NSMethod='exhaustive', the default IncludeTies and SortIndices values, and no fast-distance metric alias. Automatic residency remains transparent.

Examples

Find nearest rows

X = [0 0; 2 0; 5 0];
Y = [1 0; 4 0];
Idx = knnsearch(X,Y)

Expected output:

Idx is a 2-by-1 matrix of row indices from X.

Request distances and two neighbors

[Idx,D] = knnsearch(X,Y,"K",2)

Expected output:

Idx and D are size(Y,1)-by-2 matrices.

Include tied neighbors

Idx = knnsearch([0; 1; -1],0,"K",2,"IncludeTies",true)

Expected output:

Idx is a cell array; each cell contains all tied neighbor indices.

Using knnsearch with coding agents

Open a RunMat example with live inputs, then ask the agent to explain how knnsearch changes the result.

Run a small knnsearch example, explain the result, then change one input and compare the output.

FAQ

Does RunMat build a kd-tree?⌄

No. RunMat accepts kd-tree-related options for compatibility but currently uses exhaustive search so results stay exact.

Are custom distance functions supported?⌄

No. RunMat currently supports the standard named numeric distance metrics.

Related Stats functions

Ml

bayesopt · classify · confusionmat · crossvalind · cvpartition · fitclinear · fitctree · fitlm · kmeans · lasso · lassoglm · linkage · lscov · mnrfit · optimizableVariable · pdist · pdist2 · perfcurve · predict · regress · ridge · squareform · test · training · tsne

Summary

binocdf · boxplot · cdf · cdfplot · chi2cdf · corr · corrcoef · corrcov · cov · cov2corr · dummyvar · ecdf · filloutliers · fitdist · geomean · grpstats · harmmean · icdf · isoutlier · kstest · kurtosis · lsline · mad · mode · nanmax · normalize · normcdf · norminv · normpdf · onehotdecode · onehotencode · pdf · prctile · quantile · refline · rmse · skewness · tabulate · tcdf · tiedrank · tinv · tpdf · ttest2 · wblinv

Random

binornd · bootstrp · datasample · dividerand · exprnd · gamrnd · lhsdesign · mvnrnd · normrnd · random · randsample · rng · trnd · unidrnd · unifrnd · wblrnd

Hist

histc · histcounts · histcounts2

Options

statget · statset

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how knnsearch is executed, line by line, in Rust.

  • View the source for knnsearch in Rust on GitHub
  • Learn how the RunMat runtime works
  • Found a bug? Open an issue with a minimal reproduction.

About RunMat

RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.

  • RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
  • Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • How knnsearch works
  • Examples
  • Find nearest rows
  • Request distances and two neighbors
  • Include tied neighbors
  • Using knnsearch with coding agents
  • FAQ
  • Related Stats functions
  • Ml
  • Summary
  • Random
  • Hist
  • Options
  • Open-source implementation
  • About RunMat