0% found this document useful (0 votes)
18 views3 pages

Project CFP (Inverse of Matrix)

C++ code of inverse of matrix

Uploaded by

rayyanquddusi683
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views3 pages

Project CFP (Inverse of Matrix)

C++ code of inverse of matrix

Uploaded by

rayyanquddusi683
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

#include<iostream>

using namespace std ;


const int MAX=5;
void input_matrix( float A[][MAX] , int r , int c);
void output_matrix(float A[][MAX] , int r , int c);
void Swap(float &a , float &b);
int main ()
{
float A[MAX][MAX] , I[MAX][MAX] ;
int r , c , count = 0;
cout<<"Input dimensions of matrix ";
cin>>r>>c;
input_matrix(A , r ,c);
cout<<endl;
output_matrix(A , r , c);
cout<<endl;
float pivot , multi;
// Identity matrix input
for (int i=0 ; i<r ; i++)
{
for (int j=0 ; j<c ; j++)
{
if (i==j)
{
I[i][j]=1;
}
else
{
I[i][j]=0;
}
}
}
// Main functioning of converting matrix in reduced echelon form
for (int i=0 ; i<r ; i++)
{
// If First element of row is zero now swap it with other rows
for (int j=i+1 ; j<r ; j++)
{
if (A[i][i]!=0)
{
break;
}
else if (A[j][i]!=0)
{
for (int k=0 ; k<c ; k++)
{
Swap(A[i][k] , A[j][k]);
Swap(I[i][k] , I[j][k]);
}
}
}
// Making pivot point = 1 ;
if (A[i][i]!=0)
{
pivot = A[i][i];
for (int l=0 ; l<c ; l++)
{
A[i][l] = A[i][l] / pivot ;
I[i][l] = I[i][l] / pivot ;
}
for (int m = i+1 ; m<r ; m++)
{
multi = A[m][i];
for (int n=0 ; n<c ; n++)
{
A[m][n] = A[m][n] - A[i][n]*multi;
I[m][n] = I[m][n] - I[i][n]*multi;
}
}
}
}
// now convert it into reduced echelon form
float mi ;
for (int i = r-1 ; i>=0 ; i--)
{
for (int m=i-1 ; m>=0 ; m--)
{
mi = A[m][i];
for (int n=c-1 ; n>=0 ; n--)
{
A[m][n] = A[m][n] - A[i][n]*mi;
I[m][n] = I[m][n] - I[i][n]*mi;
}
}
}
// Calculating rank of matrix ;
for (int i=0 ; i<r ; i++)
{
for (int j=0 ; j<c ; j++)
{
if (A[i][j]!=0)
{
count++;
break;
}
}
}
if (count==r && count==c)
{
cout<<"Inverse of matrix exist "<<endl;
output_matrix(I , r , c);
}
else
{
cout<<"Rank of matrix is not equal to dimensions of matrix hence no inverse
exist ";
}
}

void input_matrix(float A[][MAX] , int r , int c )


{
for (int i=0 ;i<r ; i++)
{
for (int j=0 ; j<c ; j++)
{
cout<<"Enter element no ["<<i+1<<"]["<<j+1<<"]";
cin>>A[i][j];
}
}
return ;
}
void output_matrix(float A[][MAX] , int r , int c)
{
for (int i=0 ;i<r ; i++)
{
for(int j=0 ; j<c ; j++)
{
cout<<A[i][j]<<" ";
}
cout<<endl;
}
return ;
}
void Swap(float &a , float &b)
{
float temp ;
temp = a ;
a = b;
b = temp ;
return ;
}

You might also like