function [medias, b] = kmeans2(datos, num_medias)

ndatos = length(datos(:,1));
dim = length(datos(1,:));


medias = zeros(num_medias, dim);
np  = zeros(num_medias, dim);

medias = datos(1:num_medias, :);

medias_old = medias;
if (dim == 2) plot(medias(:,1), medias(:,2), 'ko'); end;
if (dim == 3) plot3(medias(:,1), medias(:,2), medias(:,3), 'ko'), end; 

for iter = 1 :100
    for k = 1: ndatos
        dist = distancia(datos(k,:),  medias(1, :));
        b(k) = 1;
        for ii = 2 :num_medias 
            aux = distancia(datos(k,:), medias(ii, :));
            if( dist > aux) 
                b(k) = ii;
                dist = aux;
            end;
        end;
    end;
    
    medias = zeros(num_medias, dim);
    np     = zeros(num_medias, dim);

    for k = 1 : ndatos
        n = b(k);
        for m = 1: dim
           medias(n, m ) = medias(n,m) + datos(k, m);
           np(n,m) = np(n,m) +1;
        end;
    end;

    for n=1: num_medias
        for m = 1 :dim
            if( np(n,m) ~= 0)
                medias(n, m) = medias(n,m) /np(n,m);
            else
                medias(n,m) = 0;
            end;
       end;
    end;

    if (dim == 2) plot(medias(:,1), medias(:,2), 'ro'), end;
    if (dim == 3) plot3(medias(:,1), medias(:,2), medias(:,3),'ro'), end;
    
    if (max(max(abs(medias_old - medias)))<0.01) 
        break;
    end;
    
    for n = 1: num_medias
        if (dim == 2) plot([medias(n,1), medias_old(n,1)],[medias(n,2), medias_old(n, 2)]), end;
        if (dim == 3) plot3([medias(n,1), medias_old(n,1)],[medias(n,2), medias_old(n, 2)],[medias(n,3), medias_old(n, 3)] ), end; 
        
    end;
    medias_old = medias;
end;

function d = distancia(dx, media)

d = 0;

n = length(dx);

for k = 1: n
    d = d + (dx(k) - media(k))^2;
end;

d = d^0.5;
