Skip to content
This repository was archived by the owner on Nov 29, 2020. It is now read-only.

Commit 8f6a8ee

Browse files
committed
MatrixInverse.cpp
1 parent 67069c1 commit 8f6a8ee

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

MatrixInverse.cpp

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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+

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@
187187
| 28 | LUPSolve.cpp | LUP Solve | 817 |
188188
| 28 | LUPSolve.cpp | LU Decomposition | 821 |
189189
| 28 | LUPSolve.cpp | LUP Decomposition | 824 |
190+
| 28 | MatrixInverse.cpp | Matrix Inverse | 828 |
190191

191192
# Supplementary Files
192193
* `utils.h`: Utils

0 commit comments

Comments
 (0)