Python Tutorials

Python Programs

Python Add Two Matrices


Python Add Two Matrices

In this tutorial, we will learn how to add two matrices in Python. We will cover the basic concept of matrix addition and implement a function to perform the operation.


What is Matrix Addition

Matrix addition is the process of adding two matrices by adding the corresponding entries together. The two matrices must have the same dimensions for the addition to be possible.


Syntax

The syntax to add two matrices in Python is:

def add_matrices(matrix1, matrix2):
    result = []
    for i in range(len(matrix1)):
        row = []
        for j in range(len(matrix1[0])):
            row.append(matrix1[i][j] + matrix2[i][j])
        result.append(row)
    return result


Adding two matrices

We can create a function to add two matrices element-wise by iterating through their elements and adding the corresponding entries.

For example,

  1. Define a function named add_matrices that takes two parameters matrix1 and matrix2.
  2. Initialize an empty list result to store the sum of the matrices.
  3. Use a nested for loop to iterate through the elements of the matrices.
  4. In the inner loop, add the corresponding elements from matrix1 and matrix2 and append the sum to a new row.
  5. Append the new row to the result list.
  6. Return the result matrix.
  7. Call the function with sample matrices and print the result.

Python Program

def add_matrices(matrix1, matrix2):
    result = []
    for i in range(len(matrix1)):
        row = []
        for j in range(len(matrix1[0])):
            row.append(matrix1[i][j] + matrix2[i][j])
        result.append(row)
    return result

# Sample matrices
matrix1 = [[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]]

matrix2 = [[9, 8, 7],
           [6, 5, 4],
           [3, 2, 1]]

# Add the matrices
result = add_matrices(matrix1, matrix2)

# Print the result
print('Sum of the matrices is:')
for row in result:
    print(row)

Output

Sum of the matrices is:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]