9#ifndef __VECTOR_SOLVER_H__
10#define __VECTOR_SOLVER_H__
18typedef std::vector<std::vector<double>> matrix;
20void swapRows(std::vector<double> &row1, std::vector<double> &row2) {
21 std::swap(row1, row2);
24const double EPS = 1e-9;
26void gaussJordan(matrix a,
int k, matrix &ans) {
27 int n = (int)a.size();
28 int m = (int)a[0].size() - k;
30 vector<int> where(m, -1);
31 for (
int col = 0, row = 0; col < m && row < n; ++col) {
33 for (
int i = row; i < n; ++i)
34 if (abs(a[i][col]) > abs(a[sel][col]))
36 if (abs(a[sel][col]) < EPS)
38 for (
int i = 0; i < m + k; ++i)
39 swap(a[sel][i], a[row][i]);
42 for (
int i = 0; i < n; ++i)
44 double c = a[i][col] / a[row][col];
45 for (
int j = col; j < m + k; ++j)
46 a[i][j] -= a[row][j] * c;
51 ans.assign(m, vector<double>(k, 0));
52 for (
int i = 0; i < m; ++i)
54 for (
int j = 0; j < k; ++j)
55 ans[i][j] = a[where[i]][m + j] / a[where[i]][i];
57 for (
int i = 0; i < n; ++i) {
58 for (
int j = 0; j < k; ++j) {
60 for (
int l = 0; l < m; ++l)
61 sum += ans[l][j] * a[i][l];
62 if (abs(sum - a[i][m + j]) > EPS)
67matrix solve(matrix &A, matrix &B) {
73 throw std::invalid_argument(
74 "Matrix dimensions are not compatible for solving AX=B");
77 matrix augmented(m, std::vector<double>(m + n));
78 for (
int i = 0; i < m; ++i) {
79 for (
int j = 0; j < m; ++j) {
80 augmented[i][j] = A[i][j];
82 for (
int j = 0; j < n; ++j) {
83 augmented[i][m + j] = B[i][j];
86 gaussJordan(augmented, B[0].size(), B);
87 matrix X(m, std::vector<double>(n));
88 for (
int i = 0; i < m; ++i) {
89 for (
int j = 0; j < n; ++j) {