function [P,C,Err]=kmeansUpdate(X,C) % function C=kmeansUpdate(X,C) % Performs 1 step of the k-means algorithm where X is p by n (data) % and C is k by n (k clusters) % P holds the sorted data % C is the new matrix of clusters % Err is a vector of distortion errors %Check to see if dimensions are correct: [m,n]=size(X); [k,p]=size(C); if n~=p error('Data dimensions do not match in kmeansUpdate\n'); end % Compute the distances from all the points to each center D=edm(X,C); % Find the minimum distance for each and sort (Idx is the vector M from the % example in the text). [Vals,Idx]=min(D,[],2); Err=zeros(k,1); %To hold the distortion errors. % Resort the data to get the new centers. for j=1:k idx=find(Idx==j); if length(idx)>0 P{j}=X(idx,:); C(j,:)=mean(P{j}); Err(j)=Err(j)+sum(Vals(idx)); end end