-
Notifications
You must be signed in to change notification settings - Fork 1
/
Matrix.js
executable file
·98 lines (89 loc) · 2.54 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
class Matrix {
constructor(array) {
if (!(array[0] instanceof Array)) {
for (let i = 0; i < array.length; i++) {
array[i] = [array[i]];
}
}
return array;
}
static add(a, b) {
let add = [];
for (let i = 0; i < a.length; i++) {
add[i] = [];
for (let j = 0; j < a[0].length; j++) {
add[i][j] = a[i][j] + b[i][j];
}
}
return add;
}
static subtract(a, b) {
let subtract = [];
for (let i = 0; i < a.length; i++) {
subtract[i] = [];
for (let j = 0; j < a[0].length; j++) {
subtract[i][j] = a[i][j] - b[i][j];
}
}
return subtract;
}
static multiply(a, b) {
let product = [];
if(!(a instanceof Array)){
for (let i = 0; i < b.length; i++) {
product[i] = [];
for (let j = 0; j < b[0].length; j++) {
product[i][j] = a * b[i][j];
}
}
} else if(!(b instanceof Array)){
for (let i = 0; i < a.length; i++) {
product[i] = [];
for (let j = 0; j < a[0].length; j++) {
product[i][j] = a[i][j] * b;
}
}
} else {
for (let i = 0; i < a.length; i++) {
product[i] = [];
for (let j = 0; j < a[0].length; j++) {
product[i][j] = a[i][j] * b[i][j];
}
}
}
return product;
}
static dot(a, b) {
let dot = [];
for (let i = 0; i < a.length; i++) {
dot[i] = [];
for (let j = 0; j < b[0].length; j++) {
dot[i][j] = 0;
for (let k = 0; k < b.length; k++) {
dot[i][j] += a[i][k] * b[k][j]
}
}
}
return dot;
}
static map(array, func) {
let result = [];
for (let i = 0; i < array.length; i++) {
result[i] = [];
for (let j = 0; j < array[0].length; j++) {
result[i][j] = func(array[i][j]);
}
}
return result;
}
static transpose(array){
let result = [];
for (let i = 0; i < array[0].length; i++) {
result[i] = [];
for (let j = 0; j < array.length; j++) {
result[i][j] = array[j][i];
}
}
return result;
}
}