用C语言写一段聚类程序
时间: 2023-11-22 16:05:07 浏览: 83
很好,我可以帮你解决这个问题。以下是一个简单的C语言聚类程序示例:
```
#include <stdio.h>
int main()
{
int i, j, k, n;
float data[50][2], centroid[3][2];
printf("Enter the number of data points: ");
scanf("%d", &n);
printf("Enter the data points: ");
for (i = 0; i < n; i++) {
scanf("%f %f", &data[i][0], &data[i][1]);
}
// Initialize centroids
centroid[0][0] = data[0][0];
centroid[0][1] = data[0][1];
centroid[1][0] = data[1][0];
centroid[1][1] = data[1][1];
centroid[2][0] = data[2][0];
centroid[2][1] = data[2][1];
// Perform k-means clustering
for (i = 0; i < 10; i++) { // number of iterations
float cluster1_sum_x = 0.0, cluster1_sum_y = 0.0, cluster2_sum_x = 0.0, cluster2_sum_y = 0.0, cluster3_sum_x = 0.0, cluster3_sum_y = 0.0;
int cluster1_count = 0, cluster2_count = 0, cluster3_count = 0;
// Assign each data point to a centroid
for (j = 0; j < n; j++) {
float distance1 = sqrt((data[j][0] - centroid[0][0])*(data[j][0] - centroid[0][0]) + (data[j][1] - centroid[0][1])*(data[j][1] - centroid[0][1]));
float distance2 = sqrt((data[j][0] - centroid[1][0])*(data[j][0] - centroid[1][0]) + (data[j][1] - centroid[1][1])*(data[j][1] - centroid[1][1]));
float distance3 = sqrt((data[j][0] - centroid[2][0])*(data[j][0] - centroid[2][0]) + (data[j][1] - centroid[2][1])*(data[j][1] - centroid[2][1]));
if (distance1 <= distance2 && distance1 <= distance3) {
cluster1_sum_x += data[j][0];
cluster1_sum_y += data[j][1];
cluster1_count++;
}
else if (distance2 <= distance1 && distance2 <= distance3) {
cluster2_sum_x += data[j][0];
cluster2_sum_y += data[j][1];
cluster2_count++;
}
else {
cluster3_sum_x += data[j][0];
cluster3_sum_y += data[j][1];
cluster3_count++;
}
}
// Update centroids
centroid[0][0] = cluster1_sum_x / cluster1_count;
centroid[0][1] = cluster1_sum_y / cluster1_count;
centroid[1][0] = cluster2_sum_x / cluster2_count;
centroid[1][1] = cluster2_sum_y / cluster2_count;
centroid[2][0] = cluster3_sum_x / cluster3_count;
centroid[2][1] = cluster3_sum_y / cluster3_count;
}
// Print the final centroids
printf("\nFinal centroids:\n");
for (k = 0; k < 3; k++) {
printf("(%f, %f)\n", centroid[k][0], centroid[k][1]);
}
return 0;
}
```
这个程序使用k-means算法对2维数据进行聚类。你可以根据你的需要对其进行修改或扩展。
阅读全文