-1

How can we find out the centroid of each cluster in k-means clustering in MATLAB. Data is quite heterogeneous in nature.So, I want to write some MATLAB code that can plot the centroid of each cluster as well as give the coordinates of each centroid. I have used the following code for clustering-

figure
plot(X(:,1),X(:,2),'.')
opts=statset('Display','final')
[idx,c]=kmeans(x,4,'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)
hold on
plot(X(idx==3,1),X(idx==3,2),'g.','MarkerSize',12)
hold on
plot(X(idx==4,1),X(idx==4,2),'y.','MarkerSize',12)
hold on
plot(C(:,1),C(:,2),'Kx',...
     'MarkerSize',15,'LineWidth',3)
legend('Cluster 1','Cluster 2','Cluster 3','Cluster 4','Centroids',...
   'Location','NW')
title 'Cluster Assignments and centroids '
hold off
Anton
  • 4,544
  • 2
  • 25
  • 31

1 Answers1

0

I modified your code a bit:

rng default; % For reproducibility
X = [randn(100,2)*0.75+ones(100,2);
    randn(100,2)*0.5-ones(100,2)];

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

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),'g.','MarkerSize',12);
plot(X(idx==4,1),X(idx==4,2),'y.','MarkerSize',12);

plot(C(:,1),C(:,2),'Kx','MarkerSize',15,'LineWidth',3);
legend('Cluster 1','Cluster 2','Cluster 3','Cluster 4','Centroids', 'Location','NW');
title('Cluster Assignments and centroids');
hold off;

for i=1:size(C, 1)
    display(['Centroid ', num2str(i), ': X1 = ', num2str(C(i, 1)), '; X2 = ', num2str(C(i, 2))]);
end

Here is the plot:

enter image description here

Here are the centroids:

Centroid 1: X1 = 1.3661; X2 = 1.7232
Centroid 2: X1 = -1.015; X2 = -1.053
Centroid 3: X1 = 1.6565; X2 = 0.36376
Centroid 4: X1 = 0.35134; X2 = 0.85358
Anton
  • 4,544
  • 2
  • 25
  • 31