function m = kmeans(x, m_old)
% k-means iteration step
% Lecture: Unsupervised Learning (C.E.Rasmussen & M.O.Franz)
% 
% for a given cloud of data points x (data points are the rows of matrix x), 
% an old set of cluster means m_old (means are the rows of m_old), compute
% new means.
%
% Copyright Matthias Franz and Carl Edward Rasmussen 2006-04-29.

k = size(m_old, 1); % number of means
n = size(x, 1);     % number of data points

% assignment step
r = zeros(n, k);  % alloc responsibility matrix
for i=1:n % for each data point
    
    % find minimum distance to means
    d = zeros(k, 1); % set distances to 0
    for j=1:k
        d(j) = norm(x(i,:) - m_old(j,:))^2; % distance of x_i to m_j
    end
    [minval, k_i] = min(d); % get index of minimum distance mean
    r(i, k_i) = 1; % update responsibility matrix
end

% update step
m = zeros(size(m_old)); % alloc new means
n_memb = sum(r, 1); % get number of cluster members as sum over columns in r
m = (r'*x); % sum over all vectors in cluster
for j=1:k % divide by number of cluster members
    if n_memb(j) > 0
        m(j,:) = m(j,:)/n_memb(j);
    end
end