About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Monday, September 2, 2013

C Program to Find Inverse Of 3 x 3 Matrix in 10 Lines

#include<stdio.h>
#include<conio.h>
//                   a         3        i          i
void reduction(float a[][6],int size,int pivot ,int col)
{
int i,j;
float factor;

  factor=a[pivot][col];

  for(i=0;i<2*size;i++)
       a[pivot][i]/=factor;

  for(i=0;i<size;i++)
      if(i!=pivot)
      {
      factor=a[i][col];
           for(j=0;j<2*size;j++)
                a[i][j]=a[i][j]-a[pivot][j]*factor;
      }
}
//--------------------------------------------------
void main()
{
float a[3][6];
int i,j;

clrscr();

for(i=0;i<3;i++)    // Append Unit Matrix
  for(j=0;j<6;j++)
    {
    if(j==i+3)
       a[i][j]=1;
    else
       a[i][j]=0;
    }

printf("\n Enter a 3 X 3 Matrix");

for(i=0;i<3;i++)
  for(j=0;j<3;j++)
    scanf("%f",&a[i][j]);

for(i=0;i<3;i++)
    reduction(a,3,i,i);

printf("\nInvers Matrix");
 for(i=0;i<3;i++)
 {
 printf("\n");
   for(j=0;j<3;j++)
    printf("%8.3f",a[i][j+3]);
 }
}

Output :
Enter a 3 X 3 Matrix
1 3 1
1 1 2
2 3 4

Invers Matrix
   2.000   9.000  -5.000
   0.000  -2.000   1.000
  -1.000  -3.000   2.000

Explanation :
Suppose we have to find Inverse of -
1 3 1
1 1 2
2 3 4
Step 1 :
  1. Create One Matrix of Size 3 x 6
  2. i.e Create 3 x 3 Matrix and Append 3 x 3 Unit Matrix
Step 2 :
  1. Factor = a[0][0]
  2. Now For First Row : Divide all Elements by Factor Itself

No comments: