K-means familiar with MATLAB

Source: Internet
Author: User
% 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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.