k-means++MATLAB代码
时间: 2023-10-01 07:06:23 浏览: 90
用于分类的K-means++聚类_扩充实现k-means聚类算法_matlab_algorithm
5星 · 资源好评率100%
以下是一个简单的 k-means MATLAB 代码示例:
% 生成数据
data = randn(100,2);
% 初始化聚类中心
k = 3;
centers = zeros(k,2);
for i = 1:k
centers(i,:) = data(randi(size(data,1)),:);
end
% 迭代 k-means
for iter = 1:10
% 分配数据到最近的聚类中心
idx = zeros(size(data,1),1);
for i = 1:size(data,1)
distances = sum((centers - repmat(data(i,:),k,1)).^2,2);
[~, idx(i)] = min(distances);
end
% 更新聚类中心
for i = 1:k
centers(i,:) = mean(data(idx==i,:),1);
end
end
% 绘制聚类结果
figure;
scatter(data(:,1),data(:,2),[],idx);
hold on;
scatter(centers(:,1),centers(:,2),100,'k','filled');
阅读全文