kmeans聚类算法一维matlab代码
时间: 2023-09-11 20:10:05 浏览: 96
kmeans聚类算法 matlab代码实现
Sure! Here's an example of K-means clustering algorithm implemented in MATLAB for one-dimensional data:
```matlab
% One-dimensional data
data = [2, 4, 10, 12, 15, 20, 22, 25, 28, 30];
% Number of clusters
k = 2;
% Randomly initialize cluster centroids
centroids = datasample(data, k, 'Replace', false);
% Number of iterations
maxIter = 10;
% Clustering process
for iter = 1:maxIter
% Assign data points to nearest centroids
distances = abs(data - centroids');
[~, labels] = min(distances, [], 2);
% Update centroids
for i = 1:k
centroids(i) = mean(data(labels == i));
end
end
% Display the results
disp("Cluster Centers:");
disp(centroids');
disp("Cluster Assignments:");
disp(labels');
```
In this example, we have a one-dimensional dataset `data` with ten data points. We set the number of clusters `k` to 2. The algorithm randomly initializes the cluster centroids and iteratively assigns data points to the nearest centroids, and updates the centroids based on the assigned data points. Finally, it displays the cluster centers and the cluster assignments.
Note that this is a basic implementation of K-means clustering for one-dimensional data and may not be suitable for all scenarios. Feel free to modify it according to your specific needs.
阅读全文