- K-maeans例子
randn('seed',0);
mu1= [2,2];
mu2= [6,6];
mu3= [10,2];
sigma= [0.5 0; 0 0.5];
t1=mvnrnd(mu1,sigma,100);
t2=mvnrnd(mu2,sigma,100);
t3=mvnrnd(mu3,sigma,100);
x=[t1;t2;t3];
[m,n]=size(x);
k=3;
u=x(randperm(m,k),:);
while 1
c= zeros(k,300);
nums= zeros(k, 1);
for i=1:m
mind = 100000;
minl = 0;
for j=1:k
d = norm(x(i,:)-u(j,:));
if (d<mind)
mind = d;
minl = j;
end
end
nums(minl) = nums(minl) + 1; c(minl, nums(minl)) = i;
end
ut = zeros(k, 2);
for i=1:k
for j=1:nums(i)
ut(i,:) = ut(i,:) + x(c(i, j), :);
end
ut(i,:) = ut(i,:)/nums(i);
end
du = norm (ut-u);
if (du < 0.1)
break;
else
u=ut;
end
end
ch='o*+.>';
for i=1:k
plot(x(c(i,1:nums(i)), 1), x(c(i,1:nums(i)), 2), ch(i));
hold on;
tc = x(c(i,1:nums(i)), :);
chl=convhull(tc);
line(tc(chl,1),tc(chl,2))
hold on;
plot(ut(i,1), ut(i,2), 'kp');
grid;
end
待续。。。