-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRow_reduced_echelon
83 lines (64 loc) · 1.71 KB
/
Row_reduced_echelon
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
#include <iostream>
#include <vector>
using namespace std;
void printMatrix(const vector<vector<int>>& matrix) {
int p = matrix.size();
int q = matrix[0].size();
for (int i = 0; i < p; ++i) {
for (int j = 0; j < q; ++j) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
void rowReform(vector<vector<int>>& matrix) {
int p = matrix.size();
int q = matrix[0].size();
int lead = 0;
for (int i = 0; i < p; ++i) {
if (lead >= q) return;
int row = i;
while (matrix[row][lead] == 0) {
row++;
if (row == p) {
row = i;
lead++;
if (lead >= q) return;
}
}
if (row != i) {
swap(matrix[row], matrix[i]);
}
int leadElement = matrix[i][lead];
for (int j = 0; j < q; ++j) {
matrix[i][j] /= leadElement;
}
for (int k = 0; k < p; ++k) {
if (k != i) {
int factor = matrix[k][lead];
for (int j = 0; j < q; ++j) {
matrix[k][j] -= factor * matrix[i][j];
}
}
}
lead++;
}
}
int main() {
int p, q;
cout << "Enter number of rows and columns: ";
cin >> p >> q;
vector<vector<int>> matrix(p, vector<int>(q));
cout << "Enter matrix elements:" << endl;
for (int i = 0; i < p; ++i) {
for (int j = 0; j < q; ++j) {
cin >> matrix[i][j];
}
}
cout << "Original Matrix:" << endl;
printMatrix(matrix);
rowReform(matrix);
cout << "Matrix after row reduction:" << endl;
printMatrix(matrix);
return 0;
}