
function [label,center] = kmeans(data,n_clus)
%get the size of matrix
[n,d] = size(data);
max_val = max(data);
min_val = min(data);
% choose random center
center = repmat(min_val,n_clus,1) + rand(n_clus,d).*repmat(max_val-min_val,n_clus,1);

label = zeros(n,1);
while(1),
   flag = 0;
   % assign patterns to closest cluster center
   for i=1:n
      mind = norm(data(i,:)-center(1,:));
      lab = 1;
      for j=2:n_clus
         dtmp=norm(data(i,:)-center(j,:));
         if (dtmp<mind)
            mind=dtmp;
            lab=j;
         end
      end
      if (lab ~= label(i))
         label(i)=lab;
         flag = 1;
      end
   end
   
   % recompute the centers
   center=zeros(n_clus,d);
   pop = zeros(n_clus);
   for i=1:n
      center(label(i),:) = center(label(i),:) + data(i,:);
      pop(label(i)) = pop(label(i))+1;
   end
   for i=1:n_clus
      if (pop(i) > 0)
         center(i,:) = center(i,:) / pop(i);
      else
         center(i,:) =  min_val + rand(1,d) .* (max_val-min_val);
      end
   end   
   if (flag==0) 
       break; 
   end;
end