kmeans聚类算法matlab例子
时间: 2023-10-07 14:06:44 浏览: 93
以下是一个基于MATLAB的K-means聚类算法的例子:
```matlab
data = [1 1; 2 1; 1 2; 2 2; 4 4; 5 4; 4 5; 5 5]; % 数据集
cluster_num = 2; % 聚类数量
[m, n] = size(data);
cluster = data(randperm(m, cluster_num), :); % 随机选择聚类中心
epoch_max = 1000; % 最大迭代次数
therad_lim = 0.001; % 中心变化阈值
epoch_num = 0;
while(epoch_num < epoch_max)
epoch_num = epoch_num + 1;
% 计算每个点到各聚类中心的欧氏距离
distance1 = sqrt(sum((data - reshape(cluster, 1, cluster_num, n)).^2, 3));
[~, index_cluster] = min(distance1, [], 2); % 分配到最近的聚类中心
% 计算新的聚类中心
for j = 1:cluster_num
cluster_new(j, :) = mean(data(index_cluster == j, :));
end
% 如果新的聚类中心和上一轮的聚类中心之间的距离和大于阈值,则更新聚类中心;否则算法结束
if (sqrt(sum((cluster_new - cluster).^2)) > therad_lim)
cluster = cluster_new;
else
break;
end
end
% 输出结果
index_cluster
cluster
```
阅读全文