上述代码可以改成让我自己输入数据吗
时间: 2024-02-11 09:08:10 浏览: 32
是的,你可以将上述代码中的数据集部分替换成用户自己输入的数据。以下是修改后的代码:
```matlab
clc;
clear;
close all;
% 用户输入数据
data = input('Please enter your data: ');
% 初始化参数
k = 3; % 聚类数目
maxIter = 10; % 最大迭代次数
[n, d] = size(data); % 样本数和维度
labels = zeros(n, 1); % 样本标签
% 初始化聚类中心
minData = min(data);
maxData = max(data);
centers = rand(k, d) .* (maxData - minData) + minData;
% 迭代聚类
for iter = 1:maxIter
% 计算样本与聚类中心的距离
distance = zeros(n, k);
for i = 1:n
for j = 1:k
distance(i, j) = norm(data(i, :) - centers(j, :));
end
end
% 分配样本到最近的聚类中心
[~, minIndex] = min(distance, [], 2);
if iter == 1
scatter(data(:, 1), data(:, 2), 10, minIndex, 'filled');
title('Initial Clustering');
xlabel('Sepal Length');
ylabel('Sepal Width');
hold on;
scatter(centers(:, 1), centers(:, 2), 100, 'k', 'filled', 'd');
hold off;
pause(1);
end
% 更新聚类中心
for i = 1:k
centers(i, :) = mean(data(minIndex == i, :));
end
% 判断是否收敛
if iter > 1 && isequal(labels, minIndex)
break;
end
labels = minIndex;
% 可视化聚类结果
scatter(data(:, 1), data(:, 2), 10, labels, 'filled');
title(['Clustering Iteration ' num2str(iter)]);
xlabel('Sepal Length');
ylabel('Sepal Width');
hold on;
scatter(centers(:, 1), centers(:, 2), 100, 'k', 'filled', 'd');
hold off;
pause(1);
end
% 显示结果
disp(['Final labels: ' num2str(labels')]);
```
在这个代码中,我们使用 `input` 函数让用户输入数据,然后按照原来的流程进行聚类,并输出聚类结果。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)