code to find the determinant of a matrix:
#include<stdio.h>
int n;
void swap(float * a,float * b)
{
float t;
t=*a;
*a=*b;
*b=t;
return;
}
void print_mat(float a[100][100])
{
int i,j;
for (i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%f ",a[i][j]);
}
printf("\n");}
}
void row_change(float * a,float * b)
{
int i;
for (i=0;i<n;i++)
{
swap (&a[i],&b[i]);
}
return;}
void row_trans(float * a,float *b,float f)
{int i;
for (i=0;i<n;i++)
{
a[i]=a[i]+f*b[i];
}
return;
}
/* int **extract(int a[s][s],int j)
{
int k,l,i;
int b[s-1][s-1];
for (k=1;k<s;k++)
{
for (i=0,l=0;l<s && l !=j;l++)
{
b[k-1][i]=a[k][l];
i++;
}
}
return b;
}*/
main ()
{
float a[100][100];
scanf("%d",&n);
int i,j,k,count=0;
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
scanf("%f",&a[i][j]);
}
}
print_mat(a);
for (i=0;i<n;i++)
{
if (a[i][i]==0)
{
for (j=i;j<n;j++)
{
if (a[j][i] !=0)
{
row_change(a[i],a[j]);
count=count+1;
break;
}
}
if (a[i][i] == 0)
{
for (j=i;j<n;j++)
{
if(a[i][j] !=0)
{
for (k=0;k<n;k++)
{ if (k !=i)
{
row_trans(a[k],a[i],-a[k][j]/a[i][j]);
}
}
break;
}
}
}
}
else
{
for (j=0;j<n;j++)
{
if (j !=i)
{
row_trans(a[j],a[i],-a[j][i]/a[i][i]);
}
}
}
}
print_mat(a);
float pro=1;
for (i=0;i<n;i++)
{
pro=pro*a[i][i];
}
if (count%2==0)
{
printf("%f\n",pro);
}
else
printf("%f\n",-1*pro);
}
you may wonder why the extract function is written there in comments...just to facilitate you get the cofactor of an element.
#include<stdio.h>
int n;
void swap(float * a,float * b)
{
float t;
t=*a;
*a=*b;
*b=t;
return;
}
void print_mat(float a[100][100])
{
int i,j;
for (i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%f ",a[i][j]);
}
printf("\n");}
}
void row_change(float * a,float * b)
{
int i;
for (i=0;i<n;i++)
{
swap (&a[i],&b[i]);
}
return;}
void row_trans(float * a,float *b,float f)
{int i;
for (i=0;i<n;i++)
{
a[i]=a[i]+f*b[i];
}
return;
}
/* int **extract(int a[s][s],int j)
{
int k,l,i;
int b[s-1][s-1];
for (k=1;k<s;k++)
{
for (i=0,l=0;l<s && l !=j;l++)
{
b[k-1][i]=a[k][l];
i++;
}
}
return b;
}*/
main ()
{
float a[100][100];
scanf("%d",&n);
int i,j,k,count=0;
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
scanf("%f",&a[i][j]);
}
}
print_mat(a);
for (i=0;i<n;i++)
{
if (a[i][i]==0)
{
for (j=i;j<n;j++)
{
if (a[j][i] !=0)
{
row_change(a[i],a[j]);
count=count+1;
break;
}
}
if (a[i][i] == 0)
{
for (j=i;j<n;j++)
{
if(a[i][j] !=0)
{
for (k=0;k<n;k++)
{ if (k !=i)
{
row_trans(a[k],a[i],-a[k][j]/a[i][j]);
}
}
break;
}
}
}
}
else
{
for (j=0;j<n;j++)
{
if (j !=i)
{
row_trans(a[j],a[i],-a[j][i]/a[i][i]);
}
}
}
}
print_mat(a);
float pro=1;
for (i=0;i<n;i++)
{
pro=pro*a[i][i];
}
if (count%2==0)
{
printf("%f\n",pro);
}
else
printf("%f\n",-1*pro);
}
you may wonder why the extract function is written there in comments...just to facilitate you get the cofactor of an element.
No comments:
Post a Comment