Last active
May 7, 2024 01:39
-
-
Save jremmen/9454479 to your computer and use it in GitHub Desktop.
js: matrix multiplication using dot product and transposition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]]" |
Great minification!
This is brilliant stuff. I'd been trying to come up with such an expression for matrix multiplication, but my "blocker" was not appreciating the fact that I first needed the "transpose" function, for which your solution is genius. I have a slightly smaller version of dotproduct:
dotproduct = (a, b) => a.reduce(sum, ai, i) => sum + ai * b[i], 0);
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
Thanks for sharing .. I used them slightly minimized as arrow functions