用matlab写k-means聚类算法
103浏览 · 2023-09-30 09:09:22
以下是用Matlab实现k-means[聚类[算法](https://geek.csdn.net/educolumn/2354e3486d804fe718dd230739581535?spm=1055.2569.3001.10083)](https://geek.csdn.net/educolumn/1227da1bd25e6dcbd725effa1e454e58?spm=1055.2569.3001.10083)的示例[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083):
% 生成数据集
rng(1);
data = [randn(100,2)*0.75+ones(100,2);
randn(100,2)*0.5-ones(100,2)];
% 初始化聚类[中心](https://geek.csdn.net/educolumn/25c0213845468cc350845cfcac056868?spm=1055.2569.3001.10083)
k = 2;
centroids = data(randperm(size(data,1),k),:);
% [迭代](https://geek.csdn.net/educolumn/0b788626ca95a378c56d60cb2acd8f0b?spm=1055.2569.3001.10083)聚类
for iter = 1:10
% 计算每个点所属的聚类
[~,cluster] = min(pdist2(data,centroids,'euclidean'),[],2);
% 更新聚类中心
for i = 1:k
centroids(i,:) = mean(data(cluster==i,:),1);
% 绘制结果
figure;
scatter(data(cluster==1,1),data(cluster==1,2),'r');
hold on;
scatter(data(cluster==2,1),data(cluster==2,2),'b');
scatter(centroids(:,1),centroids(:,2),'kx');
legend('Cluster 1','Cluster 2','Centroids');
title('K-means Clustering');
相关问题
好的,我可以帮你用 MATLAB 实现 k-means 聚类算法。K-means 算法可以将数据集分成 k 个不同的簇,