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
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
X | NumericArray | Yes | — | Observation matrix with observations in rows. |
k | NumericArray | Yes | — | Number of clusters. |
options | Any | Variadic | — | Name-value options including Distance, Start, Replicates, MaxIter, EmptyAction, Display, OnlinePhase, and Options. |
Returns
| Name | Type | Description |
|---|---|---|
idx | NumericArray | One-based cluster index for each input observation. |
C | NumericArray | Final cluster centroid matrix. |
sumd | NumericArray | Within-cluster sums of point-to-centroid distances. |
D | NumericArray | Distance from every observation to every centroid. |
Returned values from kmeans depend on how many outputs the caller requests.
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:kmeans:InvalidArgument | Inputs, cluster counts, starts, distance metrics, or name-value options are malformed. | kmeans: invalid argument |
RunMat:kmeans:Internal | RunMat cannot allocate or construct kmeans outputs. | kmeans: internal error |
How kmeans works
Xmust 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
NaNare omitted from fitting and receiveNaNin the returnedidxandDoutputs.Infvalues are rejected. - The default distance is
"sqeuclidean". Supported distances are"sqeuclidean","cityblock","cosine","correlation", and"hamming". Startsupports"plus","sample","uniform","cluster", a numerick-by-pstart matrix, or a numerick-by-p-by-rarray of replicate starts.- When
Startis numeric,kcan be[]; RunMat infers the cluster count from the first dimension of the start matrix or array. Replicatesruns 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.MaxIterlimits Lloyd iterations.EmptyActionsupports"singleton","error", and"drop".Displayis accepted for script compatibility.OnlinePhase="on"runs an additional bounded batch-refinement phase in the CPU runtime.Optionsaccepts statset-style structs.MaxIterandDisplayfields 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 matrixC, per-cluster distance sumssumd, and the observation-by-cluster distance matrixD.
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
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.