inverse of a matrix 3x3 c++ 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; // Intinializing the row for co-factor matrix;
    n=0; // Intinializing the column for co-factor matrix;
    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)   // Increasing row index when
                        n++;
                    else{
                        n = 0;   //increasing row index and resetting column index
                        m++;
                    }
                }
        }
    }




}

int determinant(int a[N][N], int k){
    int det;
    if(k==1)
        return a[0][0]; // Matrix order is 1

    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); //Finding the adjoint of the matrix



    for(int i=0; i<k ; i++){
        for(int j=0;j<k;j++){
                inverse[i][j] = adj[i][j]/(float)deter;
        }


    }

}







int main()
{

//    cout << "Enter the order of matrix:";
//    cin >> N;
    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;
}

//Sources
//https://www.geeksforgeeks.org/adjoint-inverse-matrix/
//https://scanftree.com/programs/c/c-program-to-find-the-inverse-of-the-matrix/
//https://www.youtube.com/watch?v=qLDDwT-kPAk&t=801s

Tags:

Misc Example