UNPKG

colorjs.io

Version:

Let’s get serious about color

45 lines (34 loc) 835 B
// A is m x n. B is n x p. product is m x p. export default function multiplyMatrices(A, B) { let m = A.length; if (!Array.isArray(A[0])) { // A is vector, convert to [[a, b, c, ...]] A = [A]; } if (!Array.isArray(B[0])) { // B is vector, convert to [[a], [b], [c], ...]] B = B.map(x => [x]); } let p = B[0].length; let B_cols = B[0].map((_, i) => B.map(x => x[i])); // transpose B let product = A.map(row => B_cols.map(col => { let ret = 0; if (!Array.isArray(row)) { for (let c of col) { ret += row * c; } return ret; } for (let i=0; i < row.length; i++) { ret += row[i] * (col[i] || 0); } return ret; })); if (m === 1) { product = product[0]; // Avoid [[a, b, c, ...]] } if (p === 1) { return product.map(x => x[0]); // Avoid [[a], [b], [c], ...]] } return product; }