Skip to content

Instantly share code, notes, and snippets.

@jremmen
Last active May 7, 2024 01:39
Show Gist options
  • Save jremmen/9454479 to your computer and use it in GitHub Desktop.
Save jremmen/9454479 to your computer and use it in GitHub Desktop.
js: matrix multiplication using dot product and transposition
mmultiply = function(a,b) {
return a.map(function(x,i) {
return transpose(b).map(function(y,k) {
return dotproduct(x, y)
});
});
}
dotproduct = function(a,b) {
return a.map(function(x,i) {
return a[i] * b[i];
}).reduce(function(m,n) { return m + n; });
}
transpose = function(a) {
return a[0].map(function(x,i) {
return a.map(function(y,k) {
return y[i];
})
});
}
a = [[1,2,3],[4,5,6]]
b = [[7,8],[9,10],[11,12]]
c = [[1,2,3],[4,5,6],[7,8,9]]
d = [[10,11,12],[13,14,15],[16,17,18]]
JSON.stringify(mmultiply(a,b)) // "[[58,64],[139,154]]"
JSON.stringify(mmultiply(c,d)) // "[[84,90,96],[201,216,231],[318,342,366]]"
@lil-evil
Copy link

lil-evil commented May 6, 2021

guy. i've to thanks you, like a lot! I've past at least 3/4hours to create this function to get the dot product of two array. the problem is that it don't worked with all array. so, your function save me from going crazy and nearly give up. thankkks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment