0
0
PythonProgramBeginner · 2 min read

Python Program to Add Two Matrices with Output

To add two matrices in Python, use nested loops to add corresponding elements from both matrices and store the sums in a new matrix, like result[i][j] = matrix1[i][j] + matrix2[i][j].
📋

Examples

Inputmatrix1 = [[1, 2], [3, 4]], matrix2 = [[5, 6], [7, 8]]
Output[[6, 8], [10, 12]]
Inputmatrix1 = [[0, 0], [0, 0]], matrix2 = [[0, 0], [0, 0]]
Output[[0, 0], [0, 0]]
Inputmatrix1 = [[1]], matrix2 = [[2]]
Output[[3]]
🧠

How to Think About It

To add two matrices, think of them as grids of numbers. You add each number in the first matrix to the number in the same position in the second matrix. This means you go row by row and column by column, adding pairs of numbers and saving the result in a new matrix.
📐

Algorithm

1
Get the two matrices as input.
2
Create a new matrix to store the result with the same size as the input matrices.
3
For each row index, do:
4
For each column index in that row, do:
5
Add the elements from both matrices at that position and store in the result matrix.
6
Return or print the result matrix.
💻

Code

python
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))
Output
[[6, 8], [10, 12]]
🔍

Dry Run

Let's trace adding matrices [[1, 2], [3, 4]] and [[5, 6], [7, 8]] through the code

1

Initialize variables

rows = 2, cols = 2, result = []

2

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]]

3

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]]

4

Return result

Return [[6, 8], [10, 12]]

ijmatrix1[i][j]matrix2[i][j]sumresult so far
00156[[6]]
01268[[6, 8]]
103710[[6, 8], [10]]
114812[[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

Using list comprehension
python
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))
This method is shorter and more Pythonic but may be harder to read for beginners.
Using numpy library
python
import numpy as np
m1 = np.array([[1, 2], [3, 4]])
m2 = np.array([[5, 6], [7, 8]])
print(np.add(m1, m2))
Using numpy is efficient and simple for large matrices but requires installing an external library.

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.

ApproachTimeSpaceBest For
Nested loopsO(rows * cols)O(rows * cols)Beginners and clarity
List comprehensionO(rows * cols)O(rows * cols)Concise Python code
Numpy libraryO(rows * cols)O(rows * cols)Large matrices and performance
💡
Make sure both matrices have the same size before adding to avoid errors.
⚠️
Trying to add matrices of different sizes without checking dimensions first.