kmeans代码matlab
时间: 2023-05-16 12:06:51 浏览: 87
Sure, here is an example of k-means clustering algorithm implemented in MATLAB:
```matlab
% Generate some random data
data = rand(100, 2);
% Set the number of clusters
k = 3;
% Initialize the centroids randomly
centroids = data(randperm(size(data, 1), k), :);
% Run the k-means algorithm
for i = 1:10
% Assign each data point to the nearest centroid
[~, labels] = pdist2(centroids, data, 'euclidean', 'Smallest', 1);
% Update the centroids
for j = 1:k
centroids(j, :) = mean(data(labels == j, :), 1);
end
end
% Plot the results
scatter(data(:, 1), data(:, 2), [], labels);
hold on;
scatter(centroids(:, 1), centroids(:, 2), 100, 'k', 'filled');
```
This code generates some random data and applies the k-means algorithm to cluster it into `k` clusters. The centroids are initialized randomly and updated iteratively until convergence. Finally, the results are plotted with different colors for each cluster and black circles for the centroids.
阅读全文