Python Program to Add Two Matrices with Output
result[i][j] = matrix1[i][j] + matrix2[i][j].Examples
How to Think About It
Algorithm
Code
def add_matrices(matrix1, matrix2): rows = len(matrix1) cols = len(matrix1[0]) result = [] for i in range(rows): row = [] for j in range(cols): row.append(matrix1[i][j] + matrix2[i][j]) result.append(row) return result # Example usage m1 = [[1, 2], [3, 4]] m2 = [[5, 6], [7, 8]] print(add_matrices(m1, m2))
Dry Run
Let's trace adding matrices [[1, 2], [3, 4]] and [[5, 6], [7, 8]] through the code
Initialize variables
rows = 2, cols = 2, result = []
First row addition
i = 0, row = [] Add matrix1[0][0] + matrix2[0][0] = 1 + 5 = 6 Add matrix1[0][1] + matrix2[0][1] = 2 + 6 = 8 row = [6, 8] Append row to result: result = [[6, 8]]
Second row addition
i = 1, row = [] Add matrix1[1][0] + matrix2[1][0] = 3 + 7 = 10 Add matrix1[1][1] + matrix2[1][1] = 4 + 8 = 12 row = [10, 12] Append row to result: result = [[6, 8], [10, 12]]
Return result
Return [[6, 8], [10, 12]]
| i | j | matrix1[i][j] | matrix2[i][j] | sum | result so far |
|---|---|---|---|---|---|
| 0 | 0 | 1 | 5 | 6 | [[6]] |
| 0 | 1 | 2 | 6 | 8 | [[6, 8]] |
| 1 | 0 | 3 | 7 | 10 | [[6, 8], [10]] |
| 1 | 1 | 4 | 8 | 12 | [[6, 8], [10, 12]] |
Why This Works
Step 1: Create result matrix
We create an empty list to hold the sums of each element from the two matrices.
Step 2: Loop through rows and columns
We use two loops to visit every element by row and column indexes.
Step 3: Add corresponding elements
For each position, we add the numbers from both matrices and store the sum in the result matrix.
Step 4: Return the summed matrix
After all elements are added, we return the new matrix containing all sums.
Alternative Approaches
def add_matrices_lc(m1, m2): return [[m1[i][j] + m2[i][j] for j in range(len(m1[0]))] for i in range(len(m1))] m1 = [[1, 2], [3, 4]] m2 = [[5, 6], [7, 8]] print(add_matrices_lc(m1, m2))
import numpy as np m1 = np.array([[1, 2], [3, 4]]) m2 = np.array([[5, 6], [7, 8]]) print(np.add(m1, m2))
Complexity: O(rows * cols) time, O(rows * cols) space
Time Complexity
The program visits each element once in nested loops, so time grows with the number of elements.
Space Complexity
A new matrix of the same size is created to store the sums, so space grows with input size.
Which Approach is Fastest?
Using numpy is fastest for large matrices due to optimized C code, while list comprehension is concise but similar in speed to loops.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops | O(rows * cols) | O(rows * cols) | Beginners and clarity |
| List comprehension | O(rows * cols) | O(rows * cols) | Concise Python code |
| Numpy library | O(rows * cols) | O(rows * cols) | Large matrices and performance |