-
Notifications
You must be signed in to change notification settings - Fork 1
/
matrix.js
121 lines (103 loc) · 2.47 KB
/
matrix.js
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
class Matrix {
constructor(rows, cols) {
this.rows = rows;
this.cols = cols;
this.data = [];
for (let i = 0; i < this.rows; i++) {
this.data[i] = [];
for (let j = 0; j < this.cols; j++) {
this.data[i][j] = 0;
}
}
}
add(n) {
if (n instanceof Matrix) {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
this.data[i][j] += n.data[i][j];
}
}
} else {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
this.data[i][j] += n;
}
}
}
}
multiply(n) {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
this.data[i][j] *= n;
}
}
}
static multiply(mA, mB) {
if (mA.cols !== mB.rows) {
console.log(mA.cols + " " + mB.rows);
return undefined;
}
let result = new Matrix(mA.rows, mB.cols);
let a = mA.data;
let b = mB.data;
for (let i = 0; i < result.rows; i++) {
for (let j = 0; j < result.cols; j++) {
for (let k = 0; k < mB.rows; k++) {
result.data[i][j] += a[i][k] * b[k][j];
//console.log(a[i][k]+" "+b[k][i])
}
}
}
return result;
}
randomize(v1, v2) {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
this.data[i][j] = Math.random() * v1 - v2;
}
}
}
transpose() {
let result = new Matrix(this.cols, this.rows);
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
result[j][i] += this.data[i][j];
}
}
return result;
}
map(toApply) {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
this.data[i][j] = toApply(this.data[i][j]);
}
}
}
static fromArray(inp) {
let results = new Matrix(inp.length, 1);
for (let i = 0; i < results.length; i++) {
results.data[i][0] = inp[i];
}
return results;
}
toArray() {
let result = [];
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
result.push(this.data[i][j]);
}
}
return result;
}
static subtract(a, b) {
let result = new Matrix(a.rows, a.cols);
for (let i = 0; i < a.rows; i++) {
for (let j = 0; j < a.cols; j++)
result.data[i][j] = a.data[i][j] - b.data[i][j];
}
return result;
}
print() {
console.table(this.data);
}
}