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
XNumericArrayYesObservation matrix with observations in rows.
kNumericArrayYesNumber of clusters.
optionsAnyVariadicName-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.

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.

Open-source implementation

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

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.