matlab kmeans 代码,K-means 聚类算法MATLAB代码

%———————-main function—————————–

%% Clear Memory & Command Window

clc

clear

close all

%% Generate Points

Sigma = [0.5 0.05; 0.05 0.5];

f1    = mvnrnd([0.5 0]  ,Sigma,100);

f2    = mvnrnd([0.5 0.5],Sigma,100);

f3    = mvnrnd([0.5 1]  ,Sigma,100);f4    = mvnrnd([0.5 1.5],Sigma,100);

%% K-means options

feature_vector     = F;                                 % Input

number_of_clusters = 8;                                 % Number of Clusters

Kmeans_iteration   = 40;                                % K-means Iteration

%% Test K-means

[cluster_centers, data]  = km_fun(feature_vector, number_of_clusters, Kmeans_iteration); % K-means clusterig

%% Plot

CV    = ‘+r+b+c+m+k+yorobocomokoysrsbscsmsksy’;       % Color Vector

hold on

for i = 1 : number_of_clusters

PT = feature_vector(data(:, number_of_clusters+1) == i, :);                % Find points of each cluster

plot(PT(:, 1),PT(:, 2),CV(2*i-1 : 2*i), ‘LineWidth’, 2);                   % Plot points with determined color and shape

plot(cluster_centers(:, 1), cluster_centers(:, 2), ‘*k’, ‘LineWidth’, 7);  % Plot cluster centers

end

hold off

grid on

%———————-subfunction—————————————-

%% K-means

function [CENTS, DAL] = km_fun(F, K, KMI)

CENTS = F( ceil(rand(K,1)*size(F,1)) ,:);              % Cluster Centers

DAL   = zeros(size(F,1),K+2);                          % Distances and Labels

for n = 1:KMI

for i = 1:size(F,1)

for j = 1:K

DAL(i,j) = norm(F(i,:) – CENTS(j,:)); % compute the distances to every centers

end

[Distance, CN] = min(DAL(i,1:K));                % 1:K are Distance from Cluster Centers 1:K

DAL(i,K+1) = CN;                                 % K+1 is Cluster Label

DAL(i,K+2) = Distance;                           % K+2 is Minimum Distance

end

for i = 1:K

A = (DAL(:,K+1) == i);                           % Cluster K Points

CENTS(i,:) = mean(F(A,:));                       % New Cluster Centers

if sum(isnan(CENTS(:))) ~= 0                     % If CENTS(i,:) Is Nan Then Replace It With Random Point

NC = find(isnan(CENTS(:,1)) == 1);            % Find Nan Centers

for Ind = 1:size(NC,1)

CENTS(NC(Ind),:) = F(randi(size(F,1)),:);

end

end

end

end

end

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值