
k=3;
n=100;


C1=[0,0];
C2=[1,1];
C3=[-1,-1];


SSE_2 = 1e10;
SSE_1 = 1e9;

counter = 0;

while SSE_1 < SSE_2
   disp(['number of iteration: ', num2str(counter)]);  
    
   % new cluster
   P = zeros(n,1);
   for j=1:100
        [v,i] = min( [norm(C1-X(j,:)), norm(C2-X(j,:)), norm(C3-X(j,:))] );
        P(j) = i;
   end
    
   % new center 
   temp1 = [0,0];
   temp2 = [0,0];
   temp3 = [0,0];
   n1 = 0;
   n2 = 0;
   n3 = 0;
   for j=1:n
        switch P(j)
            case 1
                temp1 = temp1 + X(j,:);
                n1 = n1 + 1;
            case 2 
                temp2 = temp2 + X(j,:);
                n2 = n2 + 1;
            case 3
                temp3 = temp3 + X(j,:);
                n3 = n3 + 1;
        end
   end
   C1 = temp1/n1;
   C2 = temp2/n2;
   C3 = temp3/n3;
   
   % new SSE
   s1 = 0;
   s2 = 0;
   s3 = 0;
   for j=1:n
       switch P(j)
           case 1
               s1 = s1 + norm(C1-X(j,:))^2;
           case 2
               s2 = s2 + norm(C2-X(j,:))^2;
           case 3
               s3 = s3 + norm(C3-X(j,:))^2;
       end
   end
   SSE_2 = SSE_1;
   SSE_1 = s1+s2+s3;
   
   counter = counter + 1;
   
end



% Output
s1 = 0;
s2 = 0;
s3 = 0;
for j=1:n
    switch P(j)
        case 1
            s1 = s1 + 1;
            Y1(s1,:) = X(j,:);
        case 2
            s2 = s2 + 1;
            Y2(s2,:) = X(j,:);
        case 3
            s3 = s3 + 1;
            Y3(s3,:) = X(j,:);
    end
end


scatter(Y1(:,1),Y1(:,2),'red');
hold on
scatter(Y2(:,1),Y2(:,2),'blue');
scatter(Y3(:,1),Y3(:,2),'green');



