Python Matrix Multiplication Code
Perform matrix multiplication in pure Python without dependencies. Run our comparison of nested loops versus optimized structures.
How it Works
Matrix multiplication is a fundamental mathematical operation in linear algebra, computer graphics, and machine learning. It involves taking two matrices and producing a third one by computing dot products of rows and columns.
To multiply matrix A by matrix B, the number of columns in A must equal the number of rows in B. The resulting matrix has the dimensions of A's rows and B's columns.
In pure Python, matrix multiplication is implemented using three nested loops. While easy to write, this O(n³) operation is slow, which is why data scientists use specialized library engines like NumPy in production.
Source Code
Pure Python matrix multiplication using nested loops and list comprehension.
def multiply_matrices(A, B):
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])
if cols_A != rows_B:
raise ValueError("Cannot multiply: column size of A must match row size of B.")
# Initialize result matrix with zeros
result = [[0 for _ in range(cols_B)] for _ in range(rows_A)]
# Iterate through rows of A
for i in range(rows_A):
# Iterate through columns of B
for j in range(cols_B):
# Iterate through rows of B (or columns of A)
for k in range(cols_A):
result[i][j] += A[i][k] * B[k][j]
return result
# 2x3 Matrix A
matrix_A = [
[1, 2, 3],
[4, 5, 6]
]
# 3x2 Matrix B
matrix_B = [
[7, 8],
[9, 10],
[11, 12]
]
print("Matrix A (2x3):", matrix_A)
print("Matrix B (3x2):", matrix_B)
res = multiply_matrices(matrix_A, matrix_B)
print("Product (2x2):", res)Matrix A (2x3): [[1, 2, 3], [4, 5, 6]]
Matrix B (3x2): [[7, 8], [9, 10], [11, 12]]
Product (2x2): [[58, 64], [139, 154]]Real-world Applications
- Mathematical graphics rendering and coordinate rotations
- Simple artificial neural network layer dot products
- Understanding algorithmic structures and nested loops
Frequently Asked Questions
Why does NumPy perform matrix multiplication so much faster?
NumPy is written in C and utilizes highly optimized BLAS/LAPACK libraries. It takes advantage of vectorization, CPU cache optimizations, and parallel execution, which standard Python loops cannot do.
What is the `@` operator in Python?
Starting with Python 3.5, the `@` symbol was introduced as a dedicated infix operator for matrix multiplication, allowing you to run `A @ B` when using numpy arrays.