Introduction
Matrix multiplication is a fundamental concept in programming, mathematics, and data science. In Python, matrix multiplication is widely used for machine learning, image processing, scientific computing, and data analytics. Knowing how to perform it efficiently can help you build faster and more optimized applications.
What Is Matrix Multiplication?
Matrix multiplication combines two matrices to form a new one by taking the dot product of rows and columns. For example, if Matrix A is of size (2×3) and Matrix B is of size (3×2), then the result Matrix C = A × B will be of size (2×2).
Mathematically
[ C[i][j] = Σ (A[i][k] × B[k][j]) ]
In simpler terms, each element of the new matrix is formed by multiplying and summing corresponding elements from rows of A and columns of B.
Method 1. Using Nested Loops (Manual Approach)
This is the most basic method and helps you understand the underlying process.
A = [[1, 2, 3], [4, 5, 6]]
B = [[7, 8], [9, 10], [11, 12]]
# Initialize result matrix with zeros
result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
# Matrix multiplication logic
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
Output
[58, 64]
[139, 154]
✅ Easy to understand but not efficient for large matrices.
Method 2. Using List Comprehension
A shorter and cleaner approach using Python’s list comprehension:
A = [[1, 2, 3], [4, 5, 6]]
B = [[7, 8], [9, 10], [11, 12]]
result = [[sum(a*b for a, b in zip(A_row, B_col)) for B_col in zip(*B)] for A_row in A]
for row in result:
print(row)
Explanation
zip(*B)transposes matrix B.The
sum(a*b...)computes dot products directly.
✅ More Pythonic than nested loops, but still slower than NumPy for large datasets.
Method 3. Using NumPy (Recommended)
NumPy is the most efficient way to perform matrix multiplication in Python.
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([[7, 8], [9, 10], [11, 12]])
# Using np.dot()
result = np.dot(A, B)
print(result)
# Or simply use the @ operator
result2 = A @ B
print(result2)
Output
[[ 58 64]
[139 154]]
✅ Fast, optimized, and perfect for scientific or machine learning applications.
Method 4. Using np.matmul()
np.matmul() is another NumPy function that performs matrix multiplication efficiently.
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([[7, 8], [9, 10], [11, 12]])
result = np.matmul(A, B)
print(result)
This method behaves similarly to np.dot() for 2D arrays but supports higher-dimensional tensor operations as well.
Common Mistakes to Avoid
❌ Using the
*operator for matrix multiplication — it performs element-wise multiplication.❌ Mismatched dimensions between matrices.
❌ Forgetting to convert Python lists to NumPy arrays before using NumPy functions.
Join the conversation! Your thoughts help the community grow.