% ==================================================== % Machine Learning k-means Matlab example % ==================================================== close all clc clear all rng default; % For reproducibility A = randn(100,2)*0.75+ones(100,2); B = randn(100,2)*0.5-ones(100,2); X = [A;B]; figure; plot(X(:,1),X(:,2),'.'); title('Randomly Generated Data'); opts = statset('Display','final'); [idx,C] = kmeans(X,3,'Distance','cityblock',... 'Replicates',5,'Options',opts); figure; plot(X(idx==1,1),X(idx==1,2),'r.','MarkerSize',12) hold on plot(X(idx==2,1),X(idx==2,2),'b.','MarkerSize',12) plot(X(idx==3,1),X(idx==3,2),'k.','MarkerSize',12) plot(C(:,1),C(:,2),'kx',... 'MarkerSize',15,'LineWidth',3) legend('Cluster 1','Cluster 2','Centroids',... 'Location','NW') title('Cluster Assignments and Centroids') hold off