Line data Source code
1 : /*
2 : * simpleMatrixOps.cpp
3 : *
4 : * Created on: 30.12.2024
5 : * Author: Markus Knodel
6 : */
7 :
8 : #include <vector>
9 : #include "simpleMatrixOps.h"
10 :
11 : namespace ug
12 : {
13 :
14 : namespace simpleMatrOps
15 : {
16 :
17 0 : double determinant_2x2(std::vector<std::vector<double>> const & matrix)
18 : {
19 0 : return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
20 : }
21 :
22 0 : double determinant_3x3(std::vector<std::vector<double>> const & matrix)
23 : {
24 : double det = 0;
25 0 : det += matrix[0][0] * ((matrix[1][1] * matrix[2][2]) - (matrix[1][2] * matrix[2][1]));
26 0 : det -= matrix[0][1] * ((matrix[1][0] * matrix[2][2]) - (matrix[1][2] * matrix[2][0]));
27 0 : det += matrix[0][2] * ((matrix[1][0] * matrix[2][1]) - (matrix[1][1] * matrix[2][0]));
28 0 : return det;
29 : }
30 :
31 0 : std::vector<double> cramerRule(std::vector<std::vector<double>> const & coefficients, std::vector<double> const & constants)
32 : {
33 :
34 0 : int n = coefficients.size(); // number of unknowns
35 :
36 : std::vector<double> solutions; // vector to store the solutions
37 :
38 : // Calculate the determinant of the coefficients matrix
39 : double det_coefficients;
40 :
41 0 : if (n == 2)
42 : {
43 0 : det_coefficients = determinant_2x2(coefficients);
44 : }
45 0 : else if (n == 3)
46 : {
47 0 : det_coefficients = determinant_3x3(coefficients);
48 : }
49 : else
50 : {
51 : UG_LOG("Error: Cramer's Rule only for 2x2 and 3x3 matrices" << std::endl);
52 : return solutions;
53 : }
54 :
55 : // Calculate the solutions for each unknown
56 0 : for (int i = 0; i < n; i++)
57 : {
58 : // Create a copy of the coefficients matrix and replace the i-th column with the constants vector
59 0 : std::vector<std::vector<double>> temp_matrix = coefficients;
60 :
61 0 : for (int j = 0; j < n; j++)
62 : {
63 0 : temp_matrix[j][i] = constants[j];
64 : }
65 :
66 : // Calculate the determinant of the modified matrix
67 : double det_temp;
68 :
69 0 : if (n == 2)
70 : {
71 0 : det_temp = determinant_2x2(temp_matrix);
72 : }
73 : else
74 : {
75 0 : det_temp = determinant_3x3(temp_matrix);
76 : }
77 :
78 : // Calculate the solution for the i-th unknown
79 0 : double solution = det_temp / det_coefficients;
80 0 : solutions.push_back(solution);
81 0 : }
82 :
83 : return solutions;
84 0 : }
85 :
86 : }
87 :
88 :
89 : }
90 :
91 :
92 :
|