找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 879|回复: 0
收起左侧

k均值算法的matlab源代码

[复制链接]
ID:475537 发表于 2019-2-10 15:20 | 显示全部楼层 |阅读模式
用于实现k均值算法的matlab源代码,简单易懂,方便理解。自己可以参考注释修改源代码,以便深入的了解该算法的本质。
  1. x1=[0 1 0 1 2 1 2 3 6 7 8 6 7 8 9 7 8 9 8 9];
  2. x2=[0 0 1 1 1 2 2 2 6 6 6 7 7 7 7 8 8 9 9 9];
  3. cities = [x1;x2];   
  4. num = size(cities,2);   
  5. m1 = round(rand()*num);   
  6. m2 = round(rand()*num);
  7. while m1==m2               
  8.     m2 = round(rand()*num);
  9. end               
  10. u1 = cities(:,m1);      
  11. u2 = cities(:,m2);
  12. u_old = [u1,u2];
  13. u_new = [u2,u1];
  14. while u_old ~= u_new   
  15.     u_old = u_new ;   
  16.     for j=1:num      
  17.         dis1 = norm(cities(:,j)-u1);  
  18.         dis2 = norm(cities(:,j)-u2);
  19.         if dis1>=dis2  c(j) = 2;   
  20.         else c(j) = 1;
  21.         end
  22.     end
  23.     index1 = find(c==1);   
  24.     index2 = find(c==2);   
  25.     sum1 = sum(cities(:,index1),2);  
  26.     sum2 = sum(cities(:,index2),2);  
  27.     u1 = sum1/length(index1);      
  28.     u2 = sum2/length(index2);     
  29.     u_new = [u1,u2];        
  30. end
  31. hold on,plot(cities(1,index1),cities(2,index1),'*');  
  32. hold on,plot(cities(1,index2),cities(2,index2),'+');  
  33. hold on,plot(u1(1),u1(2),'o',u2(1),u2(2),'o');
  34. mean = u_new;
复制代码


源程序.docx

13.37 KB, 下载次数: 2, 下载积分: 黑币 -5

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表