how to do inverse of 3x3 matrix code example
Example: inverse of a matrix 3x3 c++
#include<bits/stdc++.h>
#include <iostream>
#include <cmath>
#include <iomanip>
#define N 3
using namespace std;
void getCoFactor(int a[N][N],int b[N][N],int p,int q,int k){
int i,j,m,n;
m=0;
n=0;
for(i = 0;i < k;i++){
for(j=0;j<k;j++){
b[i][j] = 0;
if(i!=p && j!=q){
b[m][n] = a[i][j];
if(n < k-2)
n++;
else{
n = 0;
m++;
}
}
}
}
}
int determinant(int a[N][N], int k){
int det;
if(k==1)
return a[0][0];
else{
int c,s=1,b[N][N],i,j,m,n;
det = 0;
for(c = 0;c < k;c++){
getCoFactor(a,b,0,c,k);
det = det + s*(a[0][c]* determinant(b,k-1));
s = -1*s;
}
}
return det;
}
void adjoint(int a[N][N], int adj[N][N], int k){
int s = 1;
int co_fact[N][N];
for(int i=0; i<k ; i++){
for(int j=0;j<k;j++){
getCoFactor(a,co_fact,i,j,k);
s = pow(-1,(i+j));
adj[j][i] = s*determinant(co_fact,k-1);
}
}
}
void Inverse(int A[N][N], float inverse[N][N],int k){
int deter = determinant(A,N);
int adj[N][N];
adjoint(A,adj,k);
for(int i=0; i<k ; i++){
for(int j=0;j<k;j++){
inverse[i][j] = adj[i][j]/(float)deter;
}
}
}
int main()
{
int A[N][N];
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
cout << "Enter matrix at a[" << i << "]" << "[" <<j << "]" << ": " ;
cin >> A[i][j];
}
}
int deter = determinant(A,N);
if(deter == 0){
cout << "Inverse does not exist." << endl;
return false;
}
float inverse[N][N];
Inverse(A,inverse,N);
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
cout << inverse[i][j] << " ";
}
cout << endl;
}
return 0;
}