Skip to content

Instantly share code, notes, and snippets.

@jremmen
Last active May 7, 2024 01:39
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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]]"
@flox1an
Copy link

flox1an commented Aug 9, 2018

Thanks for sharing .. I used them slightly minimized as arrow functions

mmultiply = (a, b) => a.map(x => transpose(b).map(y => dotproduct(x, y)));
dotproduct = (a, b) => a.map((x, i) => a[i] * b[i]).reduce((m, n) => m + n);
transpose = a => a[0].map((x, i) => a.map(y => y[i]));

@mudroljub
Copy link

Great minification!

@pknipp
Copy link

pknipp commented Mar 5, 2021

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);

@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