用matlab写一个kmeans函数
时间: 2024-03-18 11:41:56 浏览: 67
好的,我可以为您提供一个简单的 MATLAB K-Means 函数。
```matlab
function [cluster_idx, centroid] = kmeans(data, k)
% Initialize centroids randomly
centroid = datasample(data, k, 'Replace', false);
% Initialize variables
cluster_idx = zeros(size(data,1), 1);
sse = Inf;
iter = 0;
% Continue until SSE no longer decreases
while true
% Assign each data point to the closest centroid
for i = 1:size(data,1)
distances = sum((centroid - data(i,:)).^2, 2);
[~, idx] = min(distances);
cluster_idx(i) = idx;
end
% Update centroids to the mean of their assigned data points
for j = 1:k
centroid(j,:) = mean(data(cluster_idx == j,:), 1);
end
% Compute the SSE
sse_new = 0;
for i = 1:k
sse_new = sse_new + sum(sum((data(cluster_idx == i,:) - centroid(i,:)).^2));
end
% Check if SSE has converged
if abs(sse_new - sse) < 1e-6 || iter >= 100
break;
end
% Update SSE and iteration number
sse = sse_new;
iter = iter + 1;
end
```
这个函数采用数据矩阵和聚类数量作为输入,并返回每个数据点的聚类分配和聚类中心。算法使用随机初始化来选择初始聚类中心,并在 SSE 不再减小或达到最大迭代次数时停止。
阅读全文