Finding Inverse of a matrix

Hello, I recently came across this code to find inverse of a 3x3 matrix, and I don't get a few things:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#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;
}


I always get confused with the (Index % Number) way of things, what exactly does it do here.

Thanks for your time
Last edited on
The modulo (%) returns remainder of division.

%3 returns thus 0, 1, or 2. They are valid indices to that matrix.

Lets look at the first loop. It makes three iterations: i=0, i=1, i=2
The indices, before %3 are thus
i=0: 0, 1, 2
i=1: 1, 2, 3
i=2: 2, 3, 4

Now we add the %3 and get:
i=0: 0, 1, 2
i=1: 1, 2, 0
i=2: 2, 0, 1
the (Index % Number) way of things, what exactly does it do here.


In this instance, using the modulus operator % that @Keskiverto has explained above allows you derive successive terms in things like matrix expansions by cyclic permutation.

For example, if you wanted to add 1 to each term, you would want (0,1,2) to become (1,2,3), but 3 would be outside the index allowed, so using %3 cycles the result correctly to (1,2,0).


The inverse of a matrix is given by:
(transpose of matrix of cofactors) / determinant

If you can find just one term of the inverse matrix, say B00 (counting from 0, with B the inverse matrix of A), then you can find all others just by cyclic permutation of first or second index.
For example, the (0,0) term comes from i=0,j=0 on line 32:
(cofactor A)T00 = (cofactor A)00 = a11a22-a12a21
But once you have this you can just increase the i and/or j indices and cyclically permute where necessary; e.g.
(cofactor A)T01 = (cofactor A)10 = a21a32-a22a31 , incorrectly using a 3 index, but the % allows you to correct this to
a21a02-a22a01

Note that the unusual case of having a j index coming before the i index on the right-hand side of line 32 arises from transposing a matrix in finding the inverse.
Last edited on
Topic archived. No new replies allowed.