-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdensematrix.d
74 lines (65 loc) · 1.43 KB
/
densematrix.d
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
import matrix;
import openmethods;
mixin(registerMethods);
class DenseMatrix : Matrix
{
this()
{
}
this(int rows, int cols, double[] elems)
{
assert(rows * cols == elems.length);
this.nr = rows;
this.nc = cols;
this.elems = elems.dup;
}
@property int rows() const { return nr; }
@property int cols() const { return nc; }
@property double at(int i, int j) const { return elems[i * nc + j]; }
int nr, nc;
double[] elems;
}
@method
DenseMatrix _plus(DenseMatrix a, DenseMatrix b)
{
const int nr = a.rows;
const int nc = a.cols;
assert(a.nr == b.nr);
assert(a.nc == b.nc);
auto result = new DenseMatrix;
result.nr = nr;
result.nc = nc;
result.elems.length = a.elems.length;
result.elems[] = a.elems[] + b.elems[];
return result;
}
@method
DenseMatrix _plus(Matrix m1, Matrix m2)
{
const int nr = m1.rows;
const int nc = m1.cols;
assert(nr == m2.rows);
assert(nc == m2.cols);
double[] result;
result.length = nr * nc;
int o = 0;
for (int j = 0; j < nc; ++j) {
for (int i = 0; i < nr; ++i) {
result[o++] = m1.at(i, j) + m2.at(i, j);
}
}
return new DenseMatrix(nr, nc, result);
}
@method("times")
DenseMatrix doubleTimesDense(double a, DenseMatrix b) {
auto result = new DenseMatrix;
result.nr = b.nr;
result.nc = b.nc;
result.elems.length = b.elems.length;
result.elems[] = a * b.elems[];
return result;
}
@method("times")
DenseMatrix denseTimesD(DenseMatrix a, double b) {
return doubleTimesDense(b, a);
}