Explain matrix multiplication with JavaScript examples
- User
Explain matrix multiplication with JavaScript examples
- Assistant
Matrix multiplication is a fundamental operation in mathematics and programming, especially in areas like computer graphics, machine learning, and scientific computing.
🔢 What is Matrix Multiplication?
Matrix multiplication (also called the dot product) involves two matrices:
- Matrix A of size
m x n(m rows, n columns) - Matrix B of size
n x p(n rows, p columns)
The result is a matrix C of size
m x p.🧠 Rule: The number of columns of Matrix A must equal the number of rows of Matrix B.
📌 Matrix Multiplication Formula
For each entry
C[i][j]in the resultant matrixC:C[i][j] = A[i][0] * B[0][j] + A[i][1] * B[1][j] + ... + A[i][n-1] * B[n-1][j]
✅ JavaScript Code Example
Let’s implement a simple matrix multiplication function in JavaScript:
function multiplyMatrices(A, B) { const rowsA = A.length; const colsA = A[0].length; const rowsB = B.length; const colsB = B[0].length; // Validate matrices dimensions if (colsA !== rowsB) { throw new Error("Number of columns of Matrix A must match number of rows of Matrix B."); } // Create result matrix C with dimensions rowsA x colsB let result = new Array(rowsA); for (let i = 0; i < rowsA; i++) { result[i] = new Array(colsB).fill(0); } // Matrix multiplication for (let i = 0; i < rowsA; i++) { for (let j = 0; j < colsB; j++) { for (let k = 0; k < colsA; k++) { result[i][j] += A[i][k] * B[k][j]; } } } return result; }
🧪 Example Usage
const A = [ [1, 2], [3, 4] ]; const B = [ [5, 6], [7, 8] ]; const result = multiplyMatrices(A, B); console.log(result); // Output: // [ // [19, 22], // [43, 50] // ];
🧠 Explanation:
Let's calculate
result[0][0]manually:A[0] = [1, 2] B column 0 = [5, 7] result[0][0] = 1*5 + 2*7 = 5 + 14 = 19Similarly:
result[0][1] = 1*6 + 2*8 = 6 + 16 = 22 result[1][0] = 3*5 + 4*7 = 15 + 28 = 43 result[1][1] = 3*6 + 4*8 = 18 + 32 = 50So final result:
[ [19, 22], [43, 50] ]
🧰 Tips
- Use nested loops carefully; it's common to make off-by-one errors.
- For large matrices, consider using libraries like math.js, numeric.js, or TensorFlow.js for optimized performance.
Let me know if you'd like to see matrix multiplication using a library, or in a transposed format!
- Matrix A of size
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.