-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinverse.cpp
120 lines (104 loc) · 2.54 KB
/
inverse.cpp
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// C++ program to find adjoint and inverse of a matrix
#include<bits/stdc++.h>
using namespace std;
#define N 4
void getCofactor(int A[N][N], int temp[N][N], int p, int q, int n)
{
int i = 0, j = 0;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
if (row != p && col != q)
{
temp[i][j++] = A[row][col];
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
int determinant(int A[N][N], int n)
{
int D = 0; // Initialize result
if (n == 1)
return A[0][0];
int temp[N][N];
int sign = 1;
for (int f = 0; f < n; f++)
{
// Getting Cofactor of A[0][f]
getCofactor(A, temp, 0, f, n);
D += sign * A[0][f] * determinant(temp, n - 1);
sign = -sign;
}
return D;
}
void adjoint(int A[N][N],int adj[N][N])
{
if (N == 1)
{
adj[0][0] = 1;
return;
}
int sign = 1, temp[N][N];
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
// Get cofactor of A[i][j]
getCofactor(A, temp, i, j, N);
sign = ((i+j)%2==0)? 1: -1;
adj[j][i] = (sign)*(determinant(temp, N-1));
}
}
}
bool inverse(int A[N][N], float inverse[N][N])
{
// Find determinant of A[][]
int det = determinant(A, N);
if (det == 0)
{
cout << "Singular matrix, can't find its inverse";
return false;
}
// Find adjoint
int adj[N][N];
adjoint(A, adj);
// Find Inverse using formula "inverse(A) = adj(A)/det(A)"
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
inverse[i][j] = adj[i][j]/float(det);
return true;
}
template<class T>
void display(T A[N][N])
{
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
cout << A[i][j] << " ";
cout << endl;
}
}
int main()
{
int A[N][N] = { {5, -2, 2, 7},
{1, 0, 0, 3},
{-3, 1, 5, 0},
{3, -1, -9, 4}};
int adj[N][N]; // To store adjoint of A[][]
float inv[N][N]; // To store inverse of A[][]
cout << "Input matrix is :\n";
display(A);
cout << "\nThe Adjoint is :\n";
adjoint(A, adj);
display(adj);
cout << "\nThe Inverse is :\n";
if (inverse(A, inv))
display(inv);
return 0;
}