|
| 1 | +// |
| 2 | +// algorithm - some algorithms in "Introduction to Algorithms", third edition |
| 3 | +// Copyright (C) 2018 lxylxy123456 |
| 4 | +// |
| 5 | +// This program is free software: you can redistribute it and/or modify |
| 6 | +// it under the terms of the GNU Affero General Public License as |
| 7 | +// published by the Free Software Foundation, either version 3 of the |
| 8 | +// License, or (at your option) any later version. |
| 9 | +// |
| 10 | +// This program is distributed in the hope that it will be useful, |
| 11 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +// GNU Affero General Public License for more details. |
| 14 | +// |
| 15 | +// You should have received a copy of the GNU Affero General Public License |
| 16 | +// along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 17 | +// |
| 18 | + |
| 19 | +#ifndef MAIN |
| 20 | +#define MAIN |
| 21 | +#define MAIN_MatrixInverse |
| 22 | +#endif |
| 23 | + |
| 24 | +#ifndef FUNC_MatrixInverse |
| 25 | +#define FUNC_MatrixInverse |
| 26 | + |
| 27 | +#include "utils.h" |
| 28 | + |
| 29 | +#include "LUPSolve.cpp" |
| 30 | + |
| 31 | +template <typename T> |
| 32 | +Matrix<T> MatrixInverse(Matrix<T>& A) { |
| 33 | + const size_t n = A.rows; |
| 34 | + Matrix<T> LU(A), ans(n, 0), b(n, 1, 0); |
| 35 | + PT pi = LUPDecomposition(LU); |
| 36 | + for (size_t i = 0; i < n; i++) { |
| 37 | + b[i][0] = 1; |
| 38 | + Matrix<T> x = LUPSolve(LU, LU, pi, b); |
| 39 | + ans = ans.concat_h(x); |
| 40 | + b[i][0] = 0; |
| 41 | + } |
| 42 | + return ans; |
| 43 | +} |
| 44 | +#endif |
| 45 | + |
| 46 | +#ifdef MAIN_MatrixInverse |
| 47 | +int main(int argc, char *argv[]) { |
| 48 | + const size_t n = get_argv(argc, argv, 1, 6); |
| 49 | + std::vector<int> int_a, int_b; |
| 50 | + random_integers(int_a, -n, n, n * n); |
| 51 | + using T = double; |
| 52 | + std::vector<T> buf_a(n * n), buf_b(n); |
| 53 | + for (size_t i = 0; i < int_a.size(); i++) |
| 54 | + buf_a[i] = int_a[i]; |
| 55 | + Matrix<T> A(n, n, buf_a); |
| 56 | + std::cout << A << std::endl; |
| 57 | + Matrix<T> B = MatrixInverse(A); |
| 58 | + std::cout << B << std::endl; |
| 59 | + Matrix<T> C = SquareMatrixMultiply(A, B, (T) 0); |
| 60 | + std::cout << C << std::endl; |
| 61 | + return 0; |
| 62 | +} |
| 63 | +#endif |
| 64 | + |
0 commit comments