%%
X=[0,0;1,1;2,2;3,7;3,6;4,6;5,7;6,3;7,3;7,4];
sita=1/2;
%第一第二聚类中心
Z=X(randi(length(X(:,1))),:);
len=length(X);
distance=zeros(len,1);
for i=1:len
distance(i)=sqrt((X(i,1)-Z(1,1))^2+(X(i,2)-Z(1,2))^2);
end
k=find(distance==max(distance));
Z=[Z;X(k,:)];
D=sqrt((Z(1,1)-Z(2,1))^2+(Z(1,2)-Z(2,2))^2);
%%
%其余聚类中心
maxmin_D=D;
while maxmin_D>sita*D
k=size(Z,1);
distance=zeros(len,k);
for i=1:len
for j=1:k
distance(i,j)=sqrt((X(i,1)-Z(j,1))^2+(X(i,2)-Z(j,2))^2);
end
end
distance_1=min(distance,[],2);
maxmin_D=max(distance_1);
if maxmin_D>sita*D
w=find(distance_1==maxmin_D);
Z=[Z;X(w,:)];
end
end
%%
%分类
k=size(Z,1);
Y=zeros(len,3);
for i=1:len
distance=zeros(1,k);
for j=1:k
distance(j)=sqrt((X(i,1)-Z(j,1))^2+(X(i,2)-Z(j,2))^2);
end
Y(i,1:2)=X(i,:);
Y(i,3)=find(distance==min(distance));
end
%%
%更新分类中心
Z1=zeros(k,2);
K=zeros(k,1);
for i=1:len
K(Y(i,3))=K(Y(i,3))+1;
Z1(Y(i,3),1)=Z1(Y(i,3),1)+Y(i,1);
Z1(Y(i,3),2)=Z1(Y(i,3),2)+Y(i,2);
end
for i=1:k
Z1(i,1)=Z1(i,1)/K(i);
Z1(i,2)=Z1(i,2)/K(i);
end
%%
%再次分类
Y1=zeros(len,3);
for i=1:len
distance=zeros(1,k);
for j=1:k
distance(j)=sqrt((X(i,1)-Z1(j,1))^2+(X(i,2)-Z1(j,2))^2);
end
Y1(i,1:2)=X(i,:);
Y1(i,3)=find(distance==min(distance));
end
《模式识别导论》齐敏