Skip to content

Instantly share code, notes, and snippets.

@cazlu8
Created July 26, 2022 00:34
Show Gist options
  • Save cazlu8/b695cd3cad7af8c8de7dbb87412d168f to your computer and use it in GitHub Desktop.
Save cazlu8/b695cd3cad7af8c8de7dbb87412d168f to your computer and use it in GitHub Desktop.
sparse matrix multiplication
function matrixMultiplication (matrixA, matrixB) {
const matrixC = matrixA.map(x => matrixB[0].map(y => 0));
const lengthR = matrixA.length
const lengthC = matrixA[0].length
const lengthB = matrixB[0].length
let k = 0
for (let i = 0; i < lengthR; i++) {
k = 0
for (let j = 0; j < lengthB; j++) {
if(matrixA[i][j] === undefined || matrixB[j][k] === undefined)
continue
if(k === lengthB)
break;
if(matrixA[i][j] !== 0 && matrixB[j][k] !== 0)
matrixC[i][k] += matrixA[i][j] * matrixB[j][k]
if(j === lengthC - 1) {
j = -1;
k++;
}
}
}
return matrixC;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment