-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrix.h
99 lines (93 loc) · 2.16 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
97
98
99
#ifndef LASSOREGRESSION_MATRIX_H
#define LASSOREGRESSION_MATRIX_H
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
class Matrix
{
public:
//m*n matrix
int m, n;
vector<vector<double>> data;
Matrix(int out_m = 1, int out_n = 1) : m(out_m), n(out_n)
{
vector<double> temp(n, 0);
for (int i = 0; i < m; ++i) data.push_back(temp);
}
Matrix(const Matrix& second_matrix)
{
m = second_matrix.m;
n = second_matrix.n;
for (int i = 0; i < m; ++i)
{
vector<double> temp;
for (int j = 0; j < n; ++j)
temp.push_back(second_matrix.data[i][j]);
data.push_back(temp);
}
}
Matrix& operator=(const Matrix& second_matrix)
{
data.clear();
m = second_matrix.m;
n = second_matrix.n;
for (int i = 0; i < m; ++i)
{
vector<double> temp;
for (int j = 0; j < n; ++j)
temp.push_back(second_matrix.data[i][j]);
data.push_back(temp);
}
return *this;
}
};
Matrix operator+(const Matrix& A,const Matrix& B)
{
Matrix res(A);
if (A.m == B.m && A.n == B.n)
{
for (int i = 0; i < A.m; ++i)
{
for (int j = 0; j < A.n; ++j)
res.data[i][j] += B.data[i][j];
}
}
else
{
cerr << "Matrix parameters do not match\n";
}
return res;
}
Matrix operator*(const Matrix& A, const Matrix& B)
{
Matrix res(A.m, B.n);
if (A.n == B.m)
{
for (int i = 0; i < res.m; ++i)
{
for (int j = 0; j < res.n; ++j)
{
res.data[i][j] = 0;
for (int k = 0; k < A.n; ++k)
res.data[i][j] += A.data[i][k] * B.data[k][j];
}
}
}
else
{
cerr << "Matrix parameters do not match\n";
}
return res;
}
double norm(vector<double> vec)
{
int vectorSize = vec.size();
double result = 0.0;
for (int idx = 0; idx < vectorSize; ++idx)
{
result += pow(vec[idx], 2);
}
return sqrt(result);
}
#endif //LASSOREGRESSION_MATRIX_H