% Author: Lichuan jifunction kmeans (data, K, iterator) [M, N] = size (data); labelofcluster = zeros (1, M ); % m class label means = zeros (k, n); % K class cluster center disp ('Total number of samples: '); mdisp ('number of attributes: '); nsizeofcluster = floor (M/K) if (sizeofcluster = 0) sizeofcluter = 1; endfor I = 1: m labelofcluster (I) = Ceil (I/(m/K); endlabelofcluster % display the initial classification label for I = 1: K clustervector = find (labelofcluster = I); means (I, 1: n) = sum (data (clustervector, 1: N)/length (clustervector); endmeans % prints the initialized meansfor I = 1: iterator disp ('iterations: ') I change = 0; for j = 1: m currentsample = data (J, 1: N); min = inf; mincluster = 0; for k = 1: k Dist = SQRT (sum (ABS (currentsample-means (k, 1: N ))). ^ 2); If (Dist <min) mincluster = K; min = DIST; change = 1; end if (change = 1) labelofcluster (j) = mincluster; clustervector = find (labelofcluster = mincluster); means (mincluster, 1: n) = sum (data (clustervector, 1: N)/length (clustervector ); end end if (change = 0) disp ('clustering is completed when iteration is not completed ') I break; endendlabelofcluster
The printed script is:
kmeans(test,5,100); Cluster = DATA(find(LabelOfCluster == 1),1:n); plot(Cluster(:,1),Cluster(:,2),'r+'); hold on; Cluster = DATA(find(LabelOfCluster == 2),1:n); plot(Cluster(:,1),Cluster(:,2),'g+'); hold on; Cluster = DATA(find(LabelOfCluster == 3),1:n); plot(Cluster(:,1),Cluster(:,2),'b+'); hold on; Cluster = DATA(find(LabelOfCluster == 4),1:n); plot(Cluster(:,1),Cluster(:,2),'y*'); hold on; Cluster = DATA(find(LabelOfCluster == 5),1:n); plot(Cluster(:,1),Cluster(:,2),'b.'); hold on;