function c = kmeans(xy,k, iters)
% function c = kmeans(xy,k, iters)
%
% the points are given by xy,
% we want k clusters,
% and we want pictures

if (nargin < 2),
    k = 4;
end
if (nargin < 3),
    iters = 10;
end


%% generate initial clusters at random
n = length(xy);
c = ceil(k*rand(n,1));

colors = hsv(k);
m = zeros(k,2);


for iter = 1:iters,
  clf;
  hold on;
    
  for i = 1:k,  
    ind = find(c == i);
    plot(xy(ind,1),xy(ind,2),'x','Color',colors(i,:));
    
    m(i,:) = mean(xy(ind,:));
    plot(m(i,1),m(i,2),'o','MarkerFaceColor',colors(i,:));
    
  end
 
  %% reassign clusters
  
  for i = 1:n,
    dif = m - ones(k,1)*xy(i,:);
    [jnk,ci] = min(sum(dif.^2,2));
    c(i) = ci;
  end

  %% if a cluster is empty, assign it a vertex at random
  for i = 1:k,
      if (sum(c==i) == 0)
          c(ceil(n*rand)) = i;
      end
  end
  
pause

end