-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComputationalProject2.cpp
More file actions
103 lines (76 loc) · 2.86 KB
/
Copy pathComputationalProject2.cpp
File metadata and controls
103 lines (76 loc) · 2.86 KB
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
/*This is the second computational project of the course 'Linear Algebra', which aims to find
the solutions to a system of linear equations using Cramer's rule.
*/
#include <bits/stdc++.h>
using namespace std;
//Calculating the determinant of a matrix using Laplace expansion and recurison.
double determinant(vector<vector<double>> matrix, int n){
double det = 0;
//The Base case for calculating the determinant of a 2x2 matrix.
if(n == 2) {
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
}
vector<vector<double>> submatrix(n, vector<double>(n));
for(int x = 0; x < n; x++) {
// Creating the submatrix by excluding the first row and the current column.
for (int i = 1; i < n; i++) {
int si = 0;
for (int j = 0; j < n; j++) {
if (j == x)
continue;
submatrix[i - 1][si++] = matrix[i][j];
}
}
//Calculating the cofactor and adding it to the determinant.
double subdet = determinant(submatrix, n - 1);
if(x%2 == 0)
det += matrix[0][x]*subdet;
else
det -= matrix[0][x]*subdet;
}
return det;
}
//Replacing the ith column with the column matrix (B) of constants and returning the matrix.
vector<vector<double>> replace(vector<vector<double>> matrix, vector<double> B, int column){
for(int i = 0; i < sizeof(matrix)/sizeof(matrix[0][0]); i++){
matrix[i][column] = B[i];
}
return matrix;
}
int main(){
int n;
//Taking input of the number of variables in the system of the linear equations.
cout << "Input the number of variables: ";
cin >> n;
//The Coefficient matrix
vector<vector<double>> A(n, vector<double>(n));
//The constants' matrix
vector<double> B(n);
cout << "Input the coefficient square matrix A:" << '\n';
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
cout << "Input the constants column matrix B:" << '\n';
for(int i = 0; i < n; i++){
cin >> B[i];
}
//Calculating the determinant of matrix A.
double detA = determinant(A, n);
if(detA == 0){
cout << "This system of linear equations does not have an unique solution because determinant is zero." << '\n';
return 0;
}
cout << "The Determinant of the matrix A: " << detA << '\n';
//The array for storing the solutions.
vector<double> solution(n);
//Calculating each variable's value using Cramer's Rule.
for(int i = 0; i < n; i++){
vector<vector<double>> Ai = replace(A, B, i);
double detAi = determinant(Ai, n);
solution[i] = detAi / detA;
cout << "x" << i + 1 << " = " << solution[i] << '\n';
}
return 0;
}