-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgauss-jordan.cpp
57 lines (55 loc) · 1.68 KB
/
gauss-jordan.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
/*************** Gauss Jordan method for inverse matrix ********************/
#include<iostream>
using namespace std;
int main()
{
int i, j, k, n;
cout << "No of equations ? ";
cin >> n;
float a[10][10] = { 0 }, d;
cout << "Read all coefficients of matrix " << endl;
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
cin >> a[i][j];
for (i = 1; i <= n; i++)
for (j = 1; j <= 2 * n; j++)
if (j == (i + n))
a[i][j] = 1;
/************** partial pivoting **************/
for (i = n; i > 1; i--)
{
if (a[i - 1][1] < a[i][1])
for (j = 1; j <= n * 2; j++)
{
d = a[i][j];
a[i][j] = a[i - 1][j];
a[i - 1][j] = d;
}
}
/********** reducing to diagonal matrix ***********/
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n * 2; j++)
if (j != i)
{
d = a[j][i] / a[i][i];
for (k = 1; k <= n * 2; k++)
a[j][k] -= a[i][k] * d;
}
}
/************** reducing to unit matrix *************/
for (i = 1; i <= n; i++)
{
d = a[i][i];
for (j = 1; j <= n * 2; j++)
a[i][j] = a[i][j] / d;
}
cout << "your solutions: " << endl;
for (i = 1; i <= n; i++)
{
for (j = n + 1; j <= n * 2; j++)
cout << a[i][j] << " ";
cout << endl;
}
return 0;
}