- k loop
- Walks the shared dimension and accumulates into
result[i][j].
Perform Matrix Multiplication in JavaScript
What you’ll learn
- The row × column rule: each entry of
ABis a dot product of a row ofAwith a column ofB. - Why three nested loops appear, and why the result buffer must start at zero before accumulating sums.
- A full 3×3 program matching the classic output, a compact 2×2 second example, a live preview for the 3×3 case, and Try it (
target="_blank").
Overview
Unlike addition, matrix multiplication combines whole rows with whole columns. The middle dimension must line up: columns of the left factor equal rows of the right factor.
Two programs
3×3 reference matrices and a smaller 2×2 product you can trace by hand.
Live preview
Browser math for the same 3×3 inputs as example 1.
Rigor
Dimension rules, complexity, and contrast with element-wise multiply in the FAQ.
Prerequisites
Nested loops and arrays of arrays; comfort with summing products in inner loops.
console.log, literal matrices such as[[1, 2], [3, 4]], and fixedNfor square demos.- You already know matrix addition (same shape, add cells). Multiplication follows different rules.
What is matrix multiplication?
If A is m × n and B is n × p, then C = AB is m × p. Entry Cij is the sum, over k from 1 to n, of AikBkj.
In code with zero-based indices: C[i][j] collects sum_k A[i][k] * B[k][j].
Formula
For compatible matrices, Cij = ∑k AikBkj. Each output cell is one dot product: row i of A dotted with column j of B.
n × nBoth factors are n × n, so the product is n × n. The reference programs use n = 3 (and n = 2 in the second example).
Trace one cell
For the 3×3 sample, the top-left result entry uses row 0 of the first matrix and column 0 of the second: 1·9 + 2·6 + 3·3 = 30.
Takeaway: the inner index k is where the first matrix’s column index meets the second matrix’s row index.
Live preview
Uses the same 3×3 integer matrices as example 1. Press the button to print both factors and AB.
Algorithm
Goal: compute C = AB for compatible square matrices of fixed size (here n × n).
Zero the output
Set every result[i][j] to 0 because you will accumulate sums with +=.
Triple loop
For each i and j, add A[i][k]*B[k][j] for all k in the shared dimension.
Display A, B, and C with row-wise console.log loops.
📜 Pseudocode
function multiply(A, B, C, n): // n×n matrices
for i from 0 to n - 1:
for j from 0 to n - 1:
C[i][j] ← 0
for k from 0 to n - 1:
C[i][j] ← C[i][j] + A[i][k] * B[k][j]Multiply two 3×3 matrices
Same matrices and output pattern as the reference: multiplyMatrices fills result, displayMatrix prints with tabs.
const N = 3;
function multiplyMatrices(a, b) {
const result = [];
let i, j, k;
for (i = 0; i < N; i++) {
result[i] = [];
for (j = 0; j < N; j++) {
result[i][j] = 0;
}
}
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
for (k = 0; k < N; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
return result;
}
function displayMatrix(matrix) {
let i, j;
for (i = 0; i < N; i++) {
let line = "";
for (j = 0; j < N; j++) {
line += matrix[i][j] + "\t";
}
console.log(line);
}
}
const firstMatrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const secondMatrix = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1],
];
const result = multiplyMatrices(firstMatrix, secondMatrix);
console.log("First Matrix:");
displayMatrix(firstMatrix);
console.log("");
console.log("Second Matrix:");
displayMatrix(secondMatrix);
console.log("");
console.log("Result Matrix:");
displayMatrix(result);Explanation
The innermost index k pairs a[i][k] with b[k][j]. Initializing result to zero matters because each result[i][j] is a sum of products.
result[i][j] += a[i][k] * b[k][j];Accumulate. One product per k; repeat for all k to finish cell (i,j).
Smaller 2×2 product (easy to check by hand)
Same triple-loop pattern with N = 2. Top-left output is 1·5 + 2·7 = 19, and so on.
const N = 2;
function multiplyMatrices(a, b) {
const result = [];
for (let i = 0; i < N; i++) {
result[i] = [];
for (let j = 0; j < N; j++) {
result[i][j] = 0;
for (let k = 0; k < N; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
return result;
}
function displayMatrix(title, m) {
console.log(title);
for (let i = 0; i < N; i++) {
console.log(m[i].join(" ") + " ");
}
}
const a = [
[1, 2],
[3, 4],
];
const b = [
[5, 6],
[7, 8],
];
const r = multiplyMatrices(a, b);
displayMatrix("A", a);
console.log("");
displayMatrix("B", b);
console.log("");
displayMatrix("AB", r);Explanation
Combining zero-init with the k loop in one nest is a compact variant; mathematically it matches example 1.
Notes for larger problems
Non-square factors. Generalize loop bounds: i < rowsA, j < colsB, k < colsA (must equal rowsB).
Speed. Researchers use blocked (tile) multiplication and SIMD for huge matrices; interviews usually focus on correct triple loops first.
❓ FAQ
🔄 Input / output
Examples use literals in code. To accept typed input, read values into nested arrays (for example with prompt in the browser or readline in Node) and verify dimensions before multiplying.
Edge cases
Rules that trip beginners:
Inner dimensions
You cannot multiply m×n by p×q unless n = p.
AB vs BA
Matrix multiplication is not commutative in general: AB and BA can differ.
Integer products
Intermediate products may exceed safe integer range; consider BigInt or floating-point when inputs grow.
⏱️ Time and space complexity
| Setting | Time | Extra space |
|---|---|---|
Two n × n matrices, classic triple loop | O(n3) | O(1) beyond outputs |
m×n by n×p | O(m · n · p) | O(1) beyond outputs |
Summary
- Rule:
Cij = sumk AikBkj; inner sizes ofAandBmust match. - Code: zero
result, then three nested loops with+= a[i][k]*b[k][j]. - Complexity: cubic in
nfor squaren×nmatrices.
Matrix multiplication links rows of A with columns of B. You need A to be m × n and B to be n × p—the two n’s must match—then AB is m × p.
8 people found this page helpful
