-
Notifications
You must be signed in to change notification settings - Fork 0
/
lab_04_Inverse_GJordan.cpp
65 lines (61 loc) · 1.57 KB
/
lab_04_Inverse_GJordan.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
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
system("cls");
int size, i, j, k;
cout << "Enter no. of Unknowns: ";
cin >> size;
float a[size][size], inv[size][size], ratio;
/*Initializing Identity Matrix*/
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
if (i == j)
inv[i][j] = 1;
else
inv[i][j] = 0;
}
}
/*Input the Matrix to be Inversed*/
cout << "Enter Matrix to be Inversed: ";
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
cin >> a[i][j];
/*Gauss Jordan Method*/
for (i = 0; i < size; i++)
{
if (a[i][i] == 0)
{
cout << "Diagonal Element Cannot Be Zero!";
exit(0);
}
for (j = 0; j < size; j++)
{
ratio = a[j][i] / a[i][i];
if (i != j)
{
for (k = 0; k < size; k++)
{
a[j][k] -= ratio * a[i][k];
inv[j][k] -= ratio * inv[i][k]; // simultaneously applying row transformation to the identity matrix
}
}
}
}
/*Display the Inverse*/
cout << endl
<< "Inverse of Matrix is: " << endl;
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
inv[i][j] /= a[i][i];
cout << setw(5) << inv[i][j] << "\t";
}
cout << endl;
}
return 0;
}