用MATLAB写一段k-means聚类代码
时间: 2024-01-30 16:01:33 浏览: 90
以下是一段MATLAB中的k-means聚类代码:
% 生成随机数据
data = rand(100,2);
% 定义聚类数
k = 3;
% 随机选择初始聚类中心
centers = data(randperm(size(data,1),k),:);
% 迭代计算,直到聚类中心不再变化
while true
% 根据当前聚类中心计算每个数据点到各聚类中心的距离
distances = pdist2(data,centers);
% 找出每个数据点距离最近的聚类中心,确定其所属的聚类
[~, labels] = min(distances,[],2);
% 保存上一次的聚类中心
old_centers = centers;
% 计算新的聚类中心
for i = 1:k
centers(i,:) = mean(data(labels==i,:));
end
% 如果聚类中心不再变化,则停止迭代
if isequal(old_centers,centers)
break;
end
end
% 绘制聚类结果
figure;
scatter(data(:,1),data(:,2),10,labels);
hold on;
scatter(centers(:,1),centers(:,2),50,'k','filled');
legend('Cluster 1','Cluster 2','Cluster 3','Centroids');
title('K-means Clustering');
阅读全文
相关推荐















