MATLAB实现质心算法的代码
时间: 2023-11-06 18:07:13 浏览: 48
以下是MATLAB实现质心算法的代码:
```
function [centroid, iterations] = centroid_algorithm(X, k, max_iterations)
% X为数据矩阵,每行代表一个样本
% k为簇的个数
% max_iterations为最大迭代次数
% centroid为最终的质心矩阵
% iterations为迭代次数
% 随机选择k个样本作为初始的质心
centroid = X(randperm(size(X, 1), k), :);
for i = 1:max_iterations
% 计算每个样本与所有质心之间的距离
distances = pdist2(X, centroid);
% 找到每个样本所属的簇(即距离最小的那个质心所在的簇)
[~, labels] = min(distances, [], 2);
% 更新每个簇的质心为该簇所有样本的平均值
for j = 1:k
centroid(j, :) = mean(X(labels == j, :), 1);
end
end
iterations = i;
end
```
使用示例:
```
% 生成一些随机数据
X = randn(100, 2);
% 调用质心算法
[centroid, iterations] = centroid_algorithm(X, 3, 100);
% 绘制聚类结果
figure;
scatter(X(:, 1), X(:, 2), [], labels);
hold on;
scatter(centroid(:, 1), centroid(:, 2), 'k', 'filled');
title(sprintf('K-means clustering (k = %d, iterations = %d)', k, iterations));
```