To perform k-means clustering in MATLAB, you can use the built-in kmeans
function. Here is an example usage:
main.m380 chars18 lines
In this example, we load the fisheriris
dataset and specify that we want to cluster the data into 3 groups (k=3
). We then run the kmeans
function on the meas
variable, which contains the measurements of sepal length and width for each iris. The resulting idx
variable contains the cluster index for each data point, and C
contains the centroid coordinates for each cluster.
We then plot the results using the gscatter
function to plot the data points colored by their cluster index, and the plot
function to plot the cluster centroids as black crosses. The resulting plot shows how the data has been partitioned into the three clusters.
gistlibby LogSnag