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

kmeans — Partition observations into k clusters with k-means clustering.

kmeans(X,k) clusters the rows of a numeric observation matrix into k clusters. It supports MATLAB-style multi-output use: [idx,C,sumd,D] = kmeans(...).

Syntax

idx = kmeans(X, k)
idx = kmeans(X, k, Name, Value)
[idx, C] = kmeans(___)
[idx, C, sumd] = kmeans(___)
[idx, C, sumd, D] = kmeans(___)

Inputs

NameTypeRequiredDefaultDescription
XNumericArrayYes—Observation matrix with observations in rows.
kNumericArrayYes—Number of clusters.
optionsAnyVariadic—Name-value options including Distance, Start, Replicates, MaxIter, EmptyAction, Display, OnlinePhase, and Options.

Returns

NameTypeDescription
idxNumericArrayOne-based cluster index for each input observation.
CNumericArrayFinal cluster centroid matrix.
sumdNumericArrayWithin-cluster sums of point-to-centroid distances.
DNumericArrayDistance from every observation to every centroid.

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

Errors

IdentifierWhenMessage
RunMat:kmeans:InvalidArgumentInputs, cluster counts, starts, distance metrics, or name-value options are malformed.kmeans: invalid argument
RunMat:kmeans:InternalRunMat cannot allocate or construct kmeans outputs.kmeans: internal error

How kmeans works

  • X must be a real numeric vector or 2-D matrix. Matrix rows are observations; row and column vectors are treated as one-dimensional observations.
  • Rows containing NaN are omitted from fitting and receive NaN in the returned idx and D outputs. Inf values are rejected.
  • The default distance is "sqeuclidean". Supported distances are "sqeuclidean", "cityblock", "cosine", "correlation", and "hamming".
  • Start supports "plus", "sample", "uniform", "cluster", a numeric k-by-p start matrix, or a numeric k-by-p-by-r array of replicate starts.
  • When Start is numeric, k can be []; RunMat infers the cluster count from the first dimension of the start matrix or array.
  • Replicates runs multiple starts and returns the result with the smallest finite within-cluster objective. Numeric 3-D starts set the replicate count from their third dimension.
  • MaxIter limits Lloyd iterations. EmptyAction supports "singleton", "error", and "drop".
  • Display is accepted for script compatibility. OnlinePhase="on" runs an additional bounded batch-refinement phase in the CPU runtime.
  • Options accepts statset-style structs. MaxIter and Display fields are honored; parallel stream fields are rejected when enabled because RunMat's CPU implementation is single-process.
  • For "cityblock" and "hamming", RunMat updates centroids with component-wise medians. Other distances use mean centroids in the metric's transformed space.
  • Outputs are idx, centroid matrix C, per-cluster distance sums sumd, and the observation-by-cluster distance matrix D.
  • Typed-integer observation data, cluster counts, numeric starts, iteration controls, and numeric parallel toggles are role-specific RunMat extensions. Structural controls decode exactly; numerical solver inputs must be exactly representable at the binary64 boundary.
  • Automatic residency may gather transparently. A documented explicit floating gpuArray call preserves output provider ownership and residency or returns an error.

Examples

Cluster a two-group data set

X = [0 0; 0.2 0.1; 9.8 9.9; 10 10.1];
[idx,C,sumd,D] = kmeans(X, 2, 'Start', [0 0; 10 10])

Expected output:

`idx` assigns the first two rows to one cluster and the last two rows to the other; `C` contains two centroids.

Use cityblock distance

idx = kmeans(X, 2, 'Distance', 'cityblock', 'Replicates', 3)

Expected output:

RunMat runs three starts and returns the best cityblock clustering.

Infer k from numeric starts

[idx,C] = kmeans(X, [], 'Start', [0 0; 10 10])

Expected output:

RunMat infers two clusters from the two rows of the start matrix.

Treat missing rows consistently

idx = kmeans([1; 2; NaN; 20], 2)

Expected output:

The third `idx` element is `NaN`; the complete rows are clustered normally.

Using kmeans with coding agents

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

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

FAQ

Does RunMat match MATLAB's exact random starts?⌄

No. RunMat uses its own deterministic RNG stream behind rng, so output shapes and semantics match MATLAB but stochastic starts are not bit-for-bit identical.

Are custom distance functions supported?⌄

No. RunMat supports the common named distances and rejects custom function-handle distances explicitly.

Related Stats functions

Ml

bayesopt · classify · confusionmat · crossvalind · cvpartition · fitclinear · fitctree · fitlm · knnsearch · 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 kmeans is executed, line by line, in Rust.

  • View the source for kmeans 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 kmeans works
  • Examples
  • Cluster a two-group data set
  • Use cityblock distance
  • Infer k from numeric starts
  • Treat missing rows consistently
  • Using kmeans with coding agents
  • FAQ
  • Related Stats functions
  • Ml
  • Summary
  • Random
  • Hist
  • Options
  • Open-source implementation
  • About RunMat