%%
% k均值聚类
load fisheriris
X = meas(:,3:4) %meas是一个矩阵,每一行是一个样本,每一列代表一个特征,选择了所有行,并选择了第三列到第四列的数据
size(X)
figure; %创建一个新的图形窗口
plot(X(:,1),X(:,2),'k*','MarkerSize',5);
rng(1);
[inx,C] = kmeans(X,3) %inx是分类的索引1-3,C是质心坐标
x1 = min(X(:,1)):0.01:max(X(:,1)); %min(X(:,1))表示X的第一列中的最小值,1,591
x2 = min(X(:,2)):0.01:max(X(:,2));
[x1G,x2G] = meshgrid(x1,x2); %x1G的每一行都是x1向量的复制 x2G的每一列都是x2向量的复制
XGrid = [x1G(:),x2G(:)]; % Defines a fine grid on the plot
idx2Region = kmeans(XGrid,3,'MaxIter',1,'Start',C);
figure;
gscatter(XGrid(:,1),XGrid(:,2),idx2Region,...
[0,0.75,0.75;0.75,0,0.75;0.75,0.75,0],'..');
hold on;
plot(X(:,1),X(:,2),'k*','MarkerSize',5);
title 'Fisher''s Iris Data';
xlabel 'Petal Lengths (cm)';
ylabel 'Petal Widths (cm)';
legend('Region 1','Region 2','Region 3','Data','Location','SouthEast');
hold off;
%%
rng default
X = [randn(100,2)*0.75 + ones(100,2);
randn(100,2)*0.5 - ones(100,2)]; %在垂直方向上连接两个随机矩阵
figure;
plot(X(:,1),X(:,2), '.');
opts = statset('Display','final');
[idx,C] = kmeans(X,2,'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(C(:,1),C(:,2),'kx',...
'MarkerSize',15,'LineWidth',3)
legend('Cluster 1','Cluster 2','Centroids',...
'Location','NW')
title 'Cluster Assignments and Centroids'
hold off
%%