Python Program to Multiply Two Matrices
result[i][j] += matrix1[i][k] * matrix2[k][j] inside three loops iterating over rows and columns.Examples
How to Think About It
Algorithm
Code
def multiply_matrices(matrix1, matrix2): rows1, cols1 = len(matrix1), len(matrix1[0]) rows2, cols2 = len(matrix2), len(matrix2[0]) if cols1 != rows2: return None # Cannot multiply result = [[0 for _ in range(cols2)] for _ in range(rows1)] for i in range(rows1): for j in range(cols2): for k in range(cols1): result[i][j] += matrix1[i][k] * matrix2[k][j] return result # Example usage matrix1 = [[1, 2], [3, 4]] matrix2 = [[5, 6], [7, 8]] print(multiply_matrices(matrix1, matrix2))
Dry Run
Let's trace multiplying matrix1 = [[1, 2], [3, 4]] and matrix2 = [[5, 6], [7, 8]] through the code.
Initialize dimensions
rows1=2, cols1=2, rows2=2, cols2=2
Create result matrix
result = [[0, 0], [0, 0]]
Calculate result[0][0]
result[0][0] = 1*5 + 2*7 = 5 + 14 = 19
Calculate result[0][1]
result[0][1] = 1*6 + 2*8 = 6 + 16 = 22
Calculate result[1][0]
result[1][0] = 3*5 + 4*7 = 15 + 28 = 43
Calculate result[1][1]
result[1][1] = 3*6 + 4*8 = 18 + 32 = 50
| Element | Calculation | Value |
|---|---|---|
| result[0][0] | 1*5 + 2*7 | 19 |
| result[0][1] | 1*6 + 2*8 | 22 |
| result[1][0] | 3*5 + 4*7 | 43 |
| result[1][1] | 3*6 + 4*8 | 50 |
Why This Works
Step 1: Check matrix sizes
We ensure the number of columns in the first matrix equals the number of rows in the second matrix because this is required for multiplication.
Step 2: Prepare result matrix
We create a new matrix filled with zeros to store the multiplication results, sized by rows of the first and columns of the second matrix.
Step 3: Multiply and sum elements
For each element in the result, we multiply corresponding elements from the row of the first matrix and column of the second matrix, then add them up.
Alternative Approaches
import numpy as np matrix1 = np.array([[1, 2], [3, 4]]) matrix2 = np.array([[5, 6], [7, 8]]) result = np.dot(matrix1, matrix2) print(result.tolist())
def multiply_matrices_lc(A, B): return [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))] matrix1 = [[1, 2], [3, 4]] matrix2 = [[5, 6], [7, 8]] print(multiply_matrices_lc(matrix1, matrix2))
Complexity: O(n * m * p) time, O(n * p) space
Time Complexity
The time depends on three nested loops: rows of first matrix (n), columns of second matrix (p), and columns of first matrix/rows of second matrix (m). So it is O(n * m * p).
Space Complexity
We create a new matrix of size n by p to store results, so space complexity is O(n * p).
Which Approach is Fastest?
Using NumPy is fastest due to optimized C code, while pure Python loops are slower but more educational.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops | O(n*m*p) | O(n*p) | Learning and small matrices |
| NumPy dot | Optimized C speed | O(n*p) | Large matrices and performance |
| List comprehension | O(n*m*p) | O(n*p) | Concise code, moderate readability |