-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMatrix.cpp
70 lines (56 loc) · 970 Bytes
/
Matrix.cpp
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
#include "Matrix.h"
#include <cmath>
using namespace std;
Matrix::Matrix(int _n) : n(_n)
{ }
double Matrix::determinant()
{
double det = 0.0;
if (n == 1)
{
det = mdata[0][0];
}
else if (n == 2)
{
det = mdata[0][0] * mdata[1][1] - mdata[0][1] * mdata[1][0];
}
else
{
for (int i = 0; i < n; ++i)
{
det += pow(-1.0, (double)i) * mdata[0][i] * subMatrix(0, i).determinant();
}
}
return det;
}
Matrix Matrix::inverse()
{
Matrix inv(n);
double det = determinant();
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
inv.mdata[i][j] = pow(-1.0, (double)i + j) * subMatrix(j, i).determinant() / det;
}
}
return inv;
}
Matrix Matrix::subMatrix(int r, int c)
{
Matrix sub(n - 1);
int row = 0;
for (int i = 0; i < n; ++i)
{
if (i == r) continue;
int col = 0;
for (int j = 0; j < n; ++j)
{
if (j == c) continue;
sub.mdata[row][col] = mdata[i][j];
++col;
}
++row;
}
return sub;
}