Showing posts with label Find Inverse of a Given Matrix. Show all posts
Showing posts with label Find Inverse of a Given Matrix. Show all posts

Find Inverse of a Given Matrix


Write a Program to find inverse of a given matrix

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>

//Read Matrix
void read_mat(float a[][10],int n)
{

int i,j;
printf("\n\nEnter %d X %d matrix below:\n",n,n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%f",&a[i][j]);

}

//Write Matrix
void write_mat(float a[][10],int n)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%10.2f",a[i][j]);
printf("\n");
}
}

//Swap Rows
void swap_rows(float a[][10],int n,int i,int j)
{
int k,temp;
for(k=0;k<n;k++)
{
temp=a[i][k];
a[i][k]=a[j][k];
a[j][k]=temp;
}
}

//Multiplication of rows
void row_mult(float a[][10],int n,int i,float x)
{
int k;
for(k=0;k<n;k++)
a[i][k]*=x;
}

// Subtraction of rows
void row_sub(float a[][10],int n,int i,int j,float x)
{
int k;
for(k=0;k<n;k++)
a[j][k]-=x*a[i][k];
}

//Inverse of matrix
void inverse(float a[][10],float ia[][10],int n)
{
int i,j;
for(i=0;i1.0e-6)
break;
if(j==n)
{
printf("Inverse does not exist");
getch();
exit(0);
}
swap_rows(a,n,i,j);
swap_rows(ia,n,i,j);
}
row_mult(ia,n,i,1/a[i][i]);
row_mult(a,n,i,1/a[i][i]);
for(j=0;j<n;j++)
if(i!=j)
{
row_sub(ia,n,i,j,a[j][i]);
row_sub(a,n,i,j,a[j][i]);
}
}
}

//main function
void main()
{
float a[10][10],b[10][10];
int n;
clrscr();

//Accept Matrix
printf("\n\nEnter order of the square matrix \n");
scanf("%d",&n);
read_mat(a,n);

//inverse the matrix
inverse(a,b,n);
printf("\n \nInverse of the given square matrix is : \n");
write_mat(b,n);
getch();
}

Labels