-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix.h
96 lines (85 loc) · 1.59 KB
/
matrix.h
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#pragma once
#include <vector>
#include <cassert>
#include <algorithm>
template <typename T, size_t M, size_t N>
class matrix
{
public:
std::vector<std::vector<T>> mat;
matrix()
{
mat = std::vector<std::vector<T>>(M, std::vector<T>(N, 0));
}
T &operator()(const size_t &x, const size_t &y)
{
return mat[x][y];
}
const T &operator()(const size_t &x, const size_t &y) const
{
return mat[x][y];
}
const size_t getRows() const
{
return mat.size();
}
const size_t getCols() const
{
if (mat.size() > 0)
return mat[0].size();
else
return 0;
}
const bool isSquare(const matrix<T, M, N> &m) const
{
return m.getRows() == m.getCols();
}
void getCofactor(matrix<T, M, N> &m, matrix<T, M, N> &temp, int p, int q, int n)
{
int i = 0, j = 0;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
if (row != p && col != q)
{
temp.mat[i][j++] = m.mat[row][col];
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
const T det()
{
assert(isSquare(*this));
int n = getRows();
T D = 0;
if (n == 1)
return mat[0][0];
matrix<T, M, N> temp;
int sign = 1;
for (int f = 0; f < n; f++)
{
getCofactor(*this, temp, 0, f, n);
D += sign * mat[0][f] * temp.det();
sign = -sign;
}
return D;
}
friend std::ostream &operator<<(std::ostream &os, const matrix &m)
{
for (const auto &row : m.data)
{
for (const auto &element : row)
{
os << element << ' ';
}
os << '\n';
}
return os;
}
};