- k loop
- Walk shared dimension and accumulate into
result[i][j].
Perform Matrix Multiplication in Python
What you’ll learn
- The row x column rule: each entry in
ABis a dot product. - Why matrix multiplication needs three nested loops in the classic approach.
- Two complete Python programs (3x3 and 2x2) plus a live preview.
Overview
Matrix multiplication is not element-wise. It combines a row from the first matrix with a column from the second matrix, then sums products.
Two programs
A full 3x3 walkthrough and a smaller 2x2 practice example.
Live preview
Run the same 3x3 sample in your browser.
Core rules
Dimension compatibility, dot products, and complexity.
Prerequisites
Nested loops, list indexing, and basic matrix terminology.
- Know that a matrix can be stored as list-of-lists in Python.
- You understand loops and can trace values with indices
i,j, andk.
What is matrix multiplication?
If A is m x n and B is n x p, then AB exists and has size m x p. The key formula is C[i][j] = sum(A[i][k] * B[k][j]).
So each result cell is a dot product: one row from A with one column from B.
Formula
For each output entry, multiply matching row/column terms and sum them. In index form: C[i][j] = sum over k of A[i][k] * B[k][j].
When both matrices are n x n, the product is also n x n. This page shows 3x3 and 2x2 examples.
Trace one cell
In the 3x3 sample, top-left output is: 1*9 + 2*6 + 3*3 = 30.
Takeaway: k connects A[i][k] with B[k][j].
Live preview
Uses the same 3x3 matrices as code example 1. Click to display both inputs and the product matrix.
Algorithm
Goal: compute C = AB for compatible matrices.
Create zero result matrix
Initialize every result cell to zero before adding products.
Triple nested loop
For each i and j, loop over k and accumulate A[i][k] * B[k][j].
Print output
Display A, B, and C row by row for clear verification.
📜 Pseudocode
function multiply(A, B):
n <- size
C <- n x n matrix of zeros
for i from 0 to n - 1:
for j from 0 to n - 1:
for k from 0 to n - 1:
C[i][j] <- C[i][j] + A[i][k] * B[k][j]
return C Multiply two 3x3 matrices
Classic interview-style implementation with helper functions for multiply and display.
N = 3
def multiply_matrices(a: list[list[int]], b: list[list[int]]) -> list[list[int]]:
result = [[0 for _ in range(N)] for _ in range(N)]
for i in range(N):
for j in range(N):
for k in range(N):
result[i][j] += a[i][k] * b[k][j]
return result
def display_matrix(matrix: list[list[int]]) -> None:
for row in matrix:
print("\t".join(str(x) for x in row))
def main() -> None:
first_matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
second_matrix = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
result = multiply_matrices(first_matrix, second_matrix)
print("First Matrix:")
display_matrix(first_matrix)
print("\nSecond Matrix:")
display_matrix(second_matrix)
print("\nResult Matrix:")
display_matrix(result)
if __name__ == "__main__":
main() Explanation
The innermost loop computes one dot product for each result cell.
result[i][j] += a[i][k] * b[k][j]Accumulate: add one product per k until the cell is complete.
Smaller 2x2 product (easy to verify)
Same logic with a smaller matrix so manual checking is easier.
N = 2
def multiply_matrices(a: list[list[int]], b: list[list[int]]) -> list[list[int]]:
result = [[0 for _ in range(N)] for _ in range(N)]
for i in range(N):
for j in range(N):
for k in range(N):
result[i][j] += a[i][k] * b[k][j]
return result
def print_matrix(title: str, m: list[list[int]]) -> None:
print(title)
for row in m:
print(*row)
def main() -> None:
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
r = multiply_matrices(a, b)
print_matrix("A", a)
print()
print_matrix("B", b)
print()
print_matrix("AB", r)
if __name__ == "__main__":
main() Explanation
Top-left value is 1*5 + 2*7 = 19; this matches the first value in output.
Notes for larger problems
Non-square matrices. Use rowsA, colsA, and colsB with the check colsA == rowsB.
Performance. Advanced solutions use blocking and optimized libraries like NumPy for big matrices.
❓ FAQ
🔄 Input / output
Examples use fixed matrices in code. For custom input, parse rows into lists, validate dimensions, then run the same triple-loop logic.
Edge cases
Common beginner mistakes:
Inner dimensions mismatch
Cannot multiply unless columns of A equal rows of B.
AB is not always BA
Changing order usually changes result, and sometimes makes multiplication invalid.
Forgetting zero init
If result cells do not start at zero, accumulation gives incorrect values.
⏱️ Time and space complexity
| Setting | Time | Extra space |
|---|---|---|
Two n x n matrices, classic triple loop | O(n^3) | O(1) beyond output |
m x n by n x p | O(m*n*p) | O(1) beyond output |
Summary
- Rule:
C[i][j] = sum(A[i][k] * B[k][j]), with compatible dimensions. - Code pattern: initialize result to zeros, then use three loops.
- Complexity: cubic for square matrices with the basic algorithm.
Matrix multiplication pairs rows of A with columns of B. If A is m x n and B is n x p, then AB exists and has size m x p.
8 people found this page helpful
