KEMBAR78
Implementation of k-means clustering algorithm in C | DOCX
/***************************************************************/
/* A program that implements K-means clustering algorithm */
/***************************************************************/
#include<stdio.h>
#include<conio.h>
#include<fstream.h>
#include<dos.h>
#include<math.h>
#include"E:KMCheaderGRAP.H"
// To get number of the corresponding cluster
int get_cluster_no(double dist[][5],int i,int centers)
{
int j;
double min;
min=dist[i][0];
for(j=0;j<centers;j++)
{
if(min>dist[i][j])
{
min=dist[i][j];
}
}
for(j=0;j<centers;j++)
{
if(min==dist[i][j])
{
break;
}
}
return j;
}
void cal_new_centers(double x[],double y[],double xc[],double yc[],int points,int centers)
{
double x1[50],y1[50]; // To store data points
double dist[50][5];// dist[i][j] : Distance from i th data point to j the cluster
int i,j;
int a[5]; // a[j]: To store number of points in the j th cluster
int cluster_no[50]; // Number of the cluster the point belongs to
static int color=2;
// To compute distances to each point from centers
for(i=0;i<points;i++)
{
for(j=0;j<centers;j++)
{
// City block distance
dist[i][j]=abs(x[i]-xc[j])+abs(y[i]-yc[j]);
}
}
for(i=0;i<points;i++)
{
cluster_no[i]=get_cluster_no(dist,i,centers);
}
for(i=0;i<5;i++)
{
a[i]=0;
}
for(i=0;i<50;i++)
{
x1[i]=0;
y1[i]=0;
}
// To calculate new centers
for(i=0;i<points;i++)
{
for(j=0;j<centers;j++)
{
if(cluster_no[i]==j)
{
x1[j]+=x[i];
y1[j]+=y[i];
a[j]++;
}
}
}
setcolor(color);
color=color+3;
for(j=0;j<centers;j++)
{
xc[j]=x1[j]/a[j];
yc[j]=y1[j]/a[j];
circle(xc[j]*10,yc[j]*10,3);
}
}
void main()
{
clrscr();
ginit();
ifstream f;
double x[50],y[50]; // To store data points
double xc[5],yc[5]; // To store centers
double *p; // To store xc[] and y[] respectively
int points; // Number of points
int centers; // Number of centers
int i,j;
// Reading the data points //
f.open("E:/KMC/data/points.txt");
f>>points;
for(i=0;i<points;i++)
{
f>>x[i]>>y[i];
}
f.close();
// End of reading the data points //
// Displaying data points //
for(i=0;i<points;i++)
{
circle(x[i]*10,y[i]*10,2);
}
// End of displaying data points //
// Reading the centers //
f.open("E:/KMC/data/centers.txt");
f>>centers;
for(i=0;i<centers;i++)
{
f>>xc[i]>>yc[i];
}
f.close();
// End of reading the centers //
// Displaying initial centroids //
for(i=0;i<centers;i++)
{
setcolor(4);
circle(xc[i]*10,yc[i]*10,3);
}
// End of displaying initial centroids //
for(i=0;i<4;i++)
{
cal_new_centers(x,y,xc,yc,points,centers);
delay(500);
}
getch();
gexit();
}

Implementation of k-means clustering algorithm in C