I\'m doing a function that multiplies 2 matrices. The matrices will always have the same number of rows and columns. (2x2, 5x5, 23x23, ...)
When I print it, it doesn
Here's my ES6 soulution with math error handling:
const matrixDot = (A, B) => {
// Math error handling
const matrices = [A, B];
const cols = matrices.map((item) => item[0].length);
if (!matrices.every((item, i) => item.every((row) => row.length === cols[i])))
return console.error('All rows in a matrix must have equal amount of columns');
else if (cols[0] !== B.length)
return console.error(
'Amount of columns in the 1st matrix must match amount of rows in the 2nd matrix'
);
// Calculations
return A.map((rowA) =>
B[0].map((_, colBIndex) =>
rowA.reduce((acc, itemA, rowBIndex) => acc + itemA * B[rowBIndex][colBIndex], 0)
)
);
};
// Example
const A = [
[3, 2, 5],
[6, 4, 1],
];
const B = [
[2, 6],
[5, 3],
[1, 4],
];
console.log(matrixDot(A, B));
// [ [21, 44],
// [33, 52] ]
Here's gist if you want to bookmark it
Hope it helps somebody ;)