K-means聚类算法MATLAB代码
时间: 2023-09-29 10:02:49 浏览: 115
以下是K-means聚类算法的MATLAB代码示例:
```matlab
% 设置随机数种子
rng(1);
% 生成数据
data = [randn(100,2)*0.75+ones(100,2);
randn(100,2)*0.5-ones(100,2)];
% 设置聚类数
k = 2;
% 初始化聚类中心点
initial_centroids = kMeansInitCentroids(data, k);
% 运行K-means聚类算法
[centroids, idx] = runkMeans(data, initial_centroids, 10);
% 可视化聚类结果
plotDataPoints(data, idx, k);
```
其中,`kMeansInitCentroids`函数用于初始化聚类中心点,`runkMeans`函数用于运行K-means聚类算法,`plotDataPoints`函数用于可视化聚类结果。
以下是完整的代码:
```matlab
% K-means聚类算法MATLAB代码示例
% 清空工作区变量
clear all;
close all;
clc;
% 加载函数文件
addpath('functions');
% 设置随机数种子
rng(1);
% 生成数据
data = [randn(100,2)*0.75+ones(100,2);
randn(100,2)*0.5-ones(100,2)];
% 可视化数据
figure;
plot(data(:,1), data(:,2), 'k.');
title('Raw Data');
% 设置聚类数
k = 2;
% 初始化聚类中心点
initial_centroids = kMeansInitCentroids(data, k);
% 运行K-means聚类算法
[centroids, idx] = runkMeans(data, initial_centroids, 10);
% 可视化聚类结果
figure;
plotDataPoints(data, idx, k);
title('Clustered Data');
% 绘制聚类中心点
hold on;
plot(centroids(:,1), centroids(:,2), 'rx', 'MarkerSize', 10, 'LineWidth', 3);
hold off;
```
其中,`functions`文件夹中包含了`kMeansInitCentroids`、`runkMeans`和`plotDataPoints`三个函数的实现。
阅读全文
相关推荐















