加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

K均值聚类算法 matlab代码

(2013-04-05 23:57:15)
标签:

k均值

matlab

it

clear;
clc;
x=[0,3,2,1,5,4,6,5,6,7];
y=[0,8,2,1,3,8,3,4,4,5];
    ca1(1)=x(4);�nter of first cluster
    cb1(1)=y(4);
    ca2(1)=x(2);�nter of second cluster
    cb2(1)=y(2);
    ca3(1)=x(9);�nter of third cluster
    cb3(1)=y(9);
    d1=0;d2=0;d3=0;Z=zeros(1,3);d=0;
    suma1=ca1(1);sumb1=cb1(1);
    suma2=ca2(1);sumb2=cb2(1);
    suma3=ca3(1);sumb3=cb3(1);
    n1=1;n2=1;n3=1;
    k=1;
    t=0;
    cluster=zeros(1,10);
    ra1=0.0;
    rb1=0.0;
    ra2=0.0;
    rb2=0.0;
    ra3=0.0;
    rb3=0.0;
while t==0
    for i=1:10
    d1=(x(i)-ca1(k))^2+(y(i)-cb1(k))^2;
    d2=(x(i)-ca2(k))^2+(y(i)-cb2(k))^2;
    d3=(x(i)-ca3(k))^2+(y(i)-cb3(k))^2;
    Z=[d1,d2,d3];
    d=min(Z);
    if d==d1
        suma1=suma1+x(i);
        sumb1=sumb1+y(i);
        n1=n1+1;
        cluster(i)=1;
    elseif d==d2
        suma2=suma2+x(i);
        sumb2=sumb2+y(i);
        n2=n2+1;
        cluster(i)=2;
    elseif d==d3
        suma3=suma3+x(i);
        sumb3=sumb3+y(i);
        n3=n3+1;
        cluster(i)=3;
    end
     end
    ca1(k+1)=suma1/n1;
    cb1(k+1)=sumb1/n1;
    ca2(k+1)=suma2/n2;
    cb2(k+1)=sumb2/n2;
    ca3(k+1)=suma3/n3;
    cb3(k+1)=sumb3/n3;
    ra1=ca1(k+1)-ca1(k);
    rb1=cb1(k+1)-cb1(k);
    ra2=ca2(k+1)-ca2(k);
    rb2=cb2(k+1)-cb2(k);
    ra3=ca3(k+1)-ca3(k);
    rb3=cb3(k+1)-cb3(k);
    if((ra1<=0.0001)&&(rb1<=0.0001)&&(ra2<=0.0001)&&(rb2<=0.0001)&&(ra3<=0.0001)&&(rb3<=0.0001))% considering of accuracy, not use ra1==0 
        t=1;
    end
   k=k+1;
   
end
figure(1)
plot(x,y,'*');xlabel('x axis');ylabel('y axis');
hold on
a=[ca1(k),ca2(k),ca3(k)];
b=[cb1(k),cb2(k),cb3(k)];
plot(a,b,'or');Legend('data source','center of cluster');

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有