k-means均值聚类算法matlab代码
时间: 2023-08-13 07:11:19 浏览: 123
K均值聚类算法(k-means)matlab代码
Sure, here is an example of the k-means clustering algorithm implemented in MATLAB:
```matlab
function [centroids, assignments] = kMeansClustering(data, k)
% Initialize centroids randomly
nSamples = size(data, 1);
centroidIndices = randperm(nSamples, k);
centroids = data(centroidIndices, :);
% Initialize assignments
assignments = zeros(nSamples, 1);
% Main loop
isConverged = false;
while ~isConverged
% Assign data points to nearest centroid
oldAssignments = assignments;
distances = pdist2(data, centroids);
[~, assignments] = min(distances, [], 2);
% Update centroids
for i = 1:k
clusterData = data(assignments == i, :);
if ~isempty(clusterData)
centroids(i, :) = mean(clusterData);
end
end
% Check convergence
isConverged = isequal(oldAssignments, assignments);
end
end
```
In this code, the `kMeansClustering` function takes two input arguments: `data` (the dataset to be clustered) and `k` (the number of clusters). It returns the final centroids (`centroids`) and the assignments of data points to clusters (`assignments`).
The algorithm starts by randomly initializing the centroids. Then, it iteratively assigns each data point to the nearest centroid and updates the centroids based on the assigned data points' mean. The iterations continue until the assignments no longer change.
You can use this function by passing your dataset (`data`) and the desired number of clusters (`k`). The function will return the final centroids and cluster assignments.
Please note that this implementation assumes you have already loaded your data into a matrix called `data`, where each row represents a data point and each column represents a feature. You may need to modify the code if your data is represented differently or if you have additional requirements.
阅读全文