Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Created March 14, 2016 18:23
Show Gist options
  • Save loretoparisi/08ffc26151e67ac92029 to your computer and use it in GitHub Desktop.
Save loretoparisi/08ffc26151e67ac92029 to your computer and use it in GitHub Desktop.
Matlab KMean Clustering Example
%{
Matlab Kmean example
@author Loreto Parisi (loretoparisi at musixmatch dot com)
@2015-2016 Musixmatch Spa.
%}
%{ clean all figures and dock new figure }
close all;
figure
try
set(figure(1), 'DockControls', 'on');
jFrame = get(handle(figure(1)), 'JavaFrame');
jFrame.fHG1Client.setClientWindowStyle(1,0);
catch
end
XDATA=[randn(100,2)*0.75+ones(100,2),randn(100,2)*0.5+ones(100,2)];
%{ 4 clusters kmeans }
[idx,C] = kmeans(NN,4,'Distance','cityblock','Replicates',5,'Options',statset('Display','final'));
plot(XDATA(idx==1,1),NN(idx==1,2),'red.','MarkerSize',12);
hold on;
plot(XDATA(idx==2,1),NN(idx==2,2),'green.','MarkerSize',12);
plot(XDATA(idx==3,1),NN(idx==3,2),'blue.','MarkerSize',12);
plot(XDATA(idx==4,1),NN(idx==4,2),'yellow.','MarkerSize',12);
%{ centroids }
plot(C(:,1),C(:,2),'kx','MarkerSize',9,'LineWidth',3);
%{ legend }
legend('Cluster 1','Cluster 2','Cluster 3','Cluster 4','Centroids','Location','NW')
@loretoparisi
Copy link
Author

The script will generate a 4 dimensions vector of random numbers to calculate Kmeans clustering:

[idx,C] = kmeans(NN,4,'Distance','cityblock','Replicates',5,'Options',statset('Display','final'));

Centroid plotting is done as well:

plot(C(:,1),C(:,2),'kx','MarkerSize',9,'LineWidth',3);

kmeans

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment