Neural Mastery
← Back to Practice

Matrix Multiplication From Scratch

Difficulty: Medium · Concept: Linear Algebra — Matrices

For an (m×n)(m \times n) matrix AA and an (n×p)(n \times p) matrix BB, the product C=ABC = AB is (m×p)(m \times p), where each entry Cij=kAikBkjC_{ij} = \sum_k A_{ik} B_{kj} — the dot product of AA's row ii with BB's column jj. This is the single operation every linear layer in a neural network runs on every forward pass.

Your task: implement matmul(A, B) for matrices represented as lists of lists of numbers (no NumPy). Raise a ValueError if the inner dimensions don't match (A's number of columns must equal B's number of rows).

Implement it yourself
assert matmul([[1, 2], [3, 4]], [[5, 6], [7, 8]]) == [[19, 22], [43, 50]] assert matmul([[1, 0], [0, 1]], [[9, 8], [7, 6]]) == [[9, 8], [7, 6]] assert matmul([[1, 2, 3]], [[1], [1], [1]]) == [[6]] assert matmul([[2]], [[3]]) == [[6]]

Next: Mean Squared Error From Scratch

Last updated Sep 5, 2026Edit this pageReport an issue