-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix.product.js
More file actions
128 lines (94 loc) · 1.99 KB
/
matrix.product.js
File metadata and controls
128 lines (94 loc) · 1.99 KB
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
122
123
124
125
126
127
128
/*
The multiply function (a.k.a product) receive two arrays
that could be as the show above:
For a row vector:
[
[a, b, c]
]
For a column vector:
[
[x],
[y],
[z]
]
For rectangle row vector:
[
[a, b, c],
[d, e, f]
]
For rectangle column vector:
[
[x, i],
[y, j],
[z, k]
]
The result will be the Tensor product or a Dot product
depending on the type of arrays passed as arguments.
For example:
Dot Product:
[
[a]
]
Tensor product:
[
[a, b, c],
[d, e, f],
[g, h, i]
]
*/
module.exports = (function(){
function getSize(m){
return [m.length, m[0].length];
}
function canBeMultiply(a, b){
return a[1] === b[0] ? true : false;
}
function buildProduct(rn, cn, m){
var result = [],
tmp,
i, j;
for (i = 0; i !== rn; i++){
tmp = [];
for (j = 0; j !== cn; j++){
(function(i, j, m){
tmp.push(function(a, b){
var products = [],
k;
for (k = 0; k !== m; k++){
products.push(
a[i][k] * b[k][j]
);
}
return products.reduce(function(x, y){
return x + y;
});
});
})(i, j, m);
}
result.push(tmp);
}
return result;
}
function multiply(a, b){
var aSize = getSize(a),
bSize = getSize(b),
result = [],
products, tmp;
if (canBeMultiply(aSize, bSize)){
products = buildProduct(aSize[0], bSize[1], aSize[1]);
products.forEach(function(p){
tmp = [];
p.forEach(function(fn){
tmp.push(fn(a, b));
});
result.push(tmp);
});
} else {
throw new Error('multiply(): Cannot multiply a * b');
}
return result;
}
return {
product: multiply
};
})();