Neural Mastery
← Practice
Matrix Multiplication From Scratchmedium

Matrix Multiplication From Scratch

medium Math for ML 15–20 min

NumPy allowed · plain Python earns 15 bonus points

New to this topic? Mathematics for AI Overview
Study this concept first →
Interactive Vector Lab

Matrix Multiplication (A @ B)

Row-by-column dot products forming the product matrix C
Editable Inputs (change values live)Step 0 of 4
A (2×2):
B (2×2):
Each output cell C[i, j] is computed as the dot product of Row i of A and Column j of B.
Live Result[[19, 22], [43, 50]]

Implement 2D matrix multiplication using dot products of rows and columns, laying the foundation for dense neural network layers.

Task

Implement matmul(A, B) for 2D matrices represented as nested lists. Raise ValueError if inner dimensions do not match.

Function Signature

matmul(A: list[list[float]], B: list[list[float]]) -> list[list[float]]

Examples

Example 1: 2x2 basic case
Input: A = [[1, 2], [3, 4]] B = [[5, 6], [7, 8]]
Output: [[19, 22], [43, 50]]
Example 2: Identity matrix
Input: A = [[1, 0], [0, 1]] B = [[9, 8], [7, 6]]
Output: [[9, 8], [7, 6]]
Example 3: Row vector × column vector
Input: A = [[1, 2, 3]] B = [[1], [1], [1]]
Output: [[6]]
Example 4: 1x1 matrices
Input: A = [[2]] B = [[3]]
Output: [[6]]

Constraints

  • Libraries (NumPy) are allowed and accepted normally.
  • A plain-Python solution (no NumPy) earns 15 bonus points.
  • Must check inner dimension compatibility (cols of A == rows of B).
  • Return 2D list of numbers.
Python3Saved ✓
def matmul(A: list[list[float]], B: list[list[float]]) -> list[list[float]]:
"""A, B: list of lists (rows). Return A @ B as a list of lists.
Raise ValueError if A's row length != B's row count."""
# Your implementation here
pass

Case 1: 2x2 basic case
Input: A = [[1, 2], [3, 4]] B = [[5, 6], [7, 8]]
Expected: [[19, 22], [43, 50]]
Case 2: Identity matrix
Input: A = [[1, 0], [0, 1]] B = [[9, 8], [7, 6]]
Expected: [[9, 8], [7, 6]]
Case 3: Row vector × column vector
Input: A = [[1, 2, 3]] B = [[1], [1], [1]]
Expected: [[6]]
Case 4: 1x1 matrices
Input: A = [[2]] B = [[3]]
Expected: [[6]]