用matlab代码写一个kmeans聚类算法
时间: 2023-10-25 20:25:10 浏览: 77
Sure, I can help you with that! Here's some MATLAB code for K-means clustering:
```
function [labels, centroids] = mykmeans(X, k)
% X: n x d data matrix
% k: number of clusters
% labels: n x 1 vector of cluster labels (1 to k)
% centroids: k x d matrix of cluster centers
% random initialization of centroids
centroids = X(randperm(size(X,1), k), :);
while true
% assign each data point to closest centroid
distance = pdist2(X, centroids);
[~, labels] = min(distance, [], 2);
% update centroids
for j = 1:k
centroids(j,:) = mean(X(labels == j, :));
end
% check convergence
if centroids == old_centroids
break;
end
old_centroids = centroids;
end
```
Hope it helps! Let me know if you have any more questions or would like any further assistance.
阅读全文