Today we are going to write a program to find the inverse of matrix C++, so let’s start with the what is the inverse of a matrix.
Inverse of Matrix:
For a square matrix A, the inverse is written A-1. When A is multiplied by A-1 the result is the identity matrix I. Non-square matrices do not have inverses.
Note: Not all square matrices have inverses. A square matrix which has an inverse is called invertible or nonsingular, and a square matrix without an inverse is called non-invertible or singular.
AA-1 = A-1A = I
Example: | For matrix , its inverse is since |
AA-1 = and A-1A = . |
Program to find Inverse of a Matrix C++:
#include<iostream> using namespace std; int main(){ int mat[3][3], i, j; float determinant = 0; cout<<"Enter elements of matrix row wise:\n"; for(i = 0; i < 3; i++) for(j = 0; j < 3; j++) cin>>mat[i][j]; printf("\nGiven matrix is:"); for(i = 0; i < 3; i++){ cout<<"\n"; for(j = 0; j < 3; j++) cout<<mat[i][j]<<"\t"; } //finding determinant for(i = 0; i < 3; i++) determinant = determinant + (mat[0][i] * (mat[1][(i+1)%3] * mat[2][(i+2)%3] - mat[1][(i+2)%3] * mat[2][(i+1)%3])); cout<<"\n\ndeterminant: "<<determinant; cout<<"\n\nInverse of matrix is: \n"; for(i = 0; i < 3; i++){ for(j = 0; j < 3; j++) cout<<((mat[(j+1)%3][(i+1)%3] * mat[(j+2)%3][(i+2)%3]) - (mat[(j+1)%3][(i+2)%3] * mat[(j+2)%3][(i+1)%3]))/ determinant<<"\t"; cout<<"\n"; } return 0; }
OUTPUT:
$g++ -o main *.cpp $main Enter elements of matrix row wise: Given matrix is: 4545 1184 0 0 4197472 0 4196160 0 1289235200 determinant: 1.48138e+09 Inverse of matrix is: -0.871163 -1.17531 0 0 0.836105 0 0.26784 0.454498 1.28099