function out = kmeans2(m,k) %% kmeans.m %% a quick implementation of k-means algorithm %% %% input: %% - m, data matrix %% - k, number of clusters %% %% output: %% - [m,g], data matrix plus group membership (1..k) %% [nr,nc] = size(m) p = randperm(size(m,1)); % random initialization for i=1:k c(i,:)=m(p(i),:) end tmp = zeros(nr,1) while 1, d = dist(m,c); % object centroïd distances [z,g] = min(d,[],2); % group matrix if g == tmp, break; else tmp = g; end for i=1:k f = find(g == i) if f % compute centroïd if not empty set c(i,:) = mean(m(find(g == i),:),1); end end end out = [m,g]