-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathomputil.hpp
121 lines (103 loc) · 2.17 KB
/
omputil.hpp
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#ifndef __OMP_UTIL_HPP__
#define __OMP_UTIL_HPP__
#define MAT_INC_FACTOR (1.6)
template<typename type>
class matrix{
public:
matrix(){data=NULL; _ncol = 0; _nrow = 0;}
matrix(size_t nrow, size_t ncol){
data = new type[nrow * ncol];
_ncol = ncol;
_nrow = nrow;
std::cout<<this<<"\n";
}
~matrix(){
if(data){
delete [] data;
data=NULL;
}
}
size_t _nrow;
size_t _ncol;
type *data;
type * operator[](size_t row)
{ return &data[row*_ncol];}
};
template<typename type>
std::vector<type> mat_vec(matrix<type> &mat, std::vector<type> g){
std::vector<type> res(mat._nrow, 0.0);
for(int i = 0; i < mat._nrow; i++){
res[i] = 0.0;
for(int j = 0; j < mat._ncol; j++){
res[i] += mat[i][j] * g[j];
}
}
return res;
}
template<typename type>
std::vector<type> mat_tran_vec(matrix<type> &mat, std::vector<type> g){
std::vector<type> res(mat._ncol, 0.0);
for(int i = 0; i < mat._ncol; i++){
res[i] = 0.0;
for(int j = 0; j < mat._nrow; j++){
res[i] += mat[j][i] * g[j];
}
}
return res;
}
//naive mat_mat
template<typename type>
void mat_mat(matrix<type> &mat1, matrix<type> &mat2, matrix<type> &res){
type sum;
for(int i = 0; i < mat1._nrow; i++){
for(int j = 0; j < mat2._ncol; j++){
sum = 0.0;
for(int k = 0; k < mat2._nrow; k++){
sum += mat1[i][k] * mat2[k][j];
}
res[i][j] = sum;
}
}
}
template<typename type>
void mat_tran_mat(matrix<type> &mat1, matrix<type> &mat2, matrix<type> &res){
type sum;
for(int i = 0; i < mat1._ncol; i++){
for(int j = 0; j < mat2._ncol; j++){
sum = 0.0;
for(int k = 0; k < mat2._nrow; k++){
sum += mat1[k][i] * mat2[k][j];
}
res[i][j] = sum;
}
}
}
template<typename type>
type l2norm(type *data, size_t len){
type sum = 0.0;
for (int i = 0; i < len; ++i)
{
sum += data[i] * data[i];
}
return sqrt(sum);
}
template<typename type>
void scale(type *data, type scl, size_t len){
for (int i = 0; i < len; ++i)
{
data[i] *= scl;
}
}
template<typename type>
std::vector<type> vec_plus(
std::vector<type> a,
std::vector<type> b
){
std::vector<type> res(a.size(), 0.0);
for (int i = 0; i < a.size(); ++i)
{
res[i] = a[i] + b[i];
}
return res;
}
#endif