Python Program to Add Two Matrices

Introduction

Matrix addition is a basic operation in linear algebra, where two matrices of the same dimensions are added together by adding their corresponding elements. This tutorial will guide you through creating a Python program that adds two matrices.

Example:

  • Matrix 1:

    1 2 3
    4 5 6
    
  • Matrix 2:

    7 8 9
    1 2 3
    
  • Resultant Matrix:

    8 10 12
    5 7 9
    

Problem Statement

Create a Python program that:

  • Takes two matrices as input.
  • Checks if the matrices have the same dimensions.
  • Adds the two matrices element-wise.
  • Displays the resulting matrix.

Solution Steps

  1. Take Matrix Dimensions: Ask the user for the number of rows and columns.
  2. Initialize Two Matrices: Create two empty matrices to store the input values.
  3. Input Matrix Elements: Use nested loops to take input for each element of the two matrices.
  4. Check Dimensions: Ensure both matrices have the same dimensions.
  5. Add the Matrices: Use nested loops to add the corresponding elements of the two matrices.
  6. Display the Resultant Matrix: Print the resulting matrix in a formatted manner.

Python Program

# Python Program to Add Two Matrices
# Author: https://www.rameshfadatare.com/

# Step 1: Take the number of rows and columns as input
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))

# Step 2: Initialize two matrices
matrix1 = []
matrix2 = []

# Step 3: Input elements for the first matrix
print("Enter the elements of the first matrix:")
for i in range(rows):
    row = []
    for j in range(columns):
        element = int(input(f"Element at position ({i+1}, {j+1}): "))
        row.append(element)
    matrix1.append(row)

# Step 4: Input elements for the second matrix
print("Enter the elements of the second matrix:")
for i in range(rows):
    row = []
    for j in range(columns):
        element = int(input(f"Element at position ({i+1}, {j+1}): "))
        row.append(element)
    matrix2.append(row)

# Step 5: Initialize the resultant matrix with zeros
result_matrix = []
for i in range(rows):
    result_matrix.append([0] * columns)

# Step 6: Add the two matrices
for i in range(rows):
    for j in range(columns):
        result_matrix[i][j] = matrix1[i][j] + matrix2[i][j]

# Step 7: Display the resulting matrix
print("\nThe resultant matrix after addition is:")
for row in result_matrix:
    for element in row:
        print(element, end=" ")
    print()  # Newline after each row

Explanation

Step 1: Take the Number of Rows and Columns as Input

  • The input() function is used to take the number of rows and columns from the user. These values are converted to integers and stored in rows and columns variables.

Step 2: Initialize Two Matrices

  • Two empty lists matrix1 and matrix2 are initialized to store the elements of the matrices.

Step 3: Input Elements for the First Matrix

  • A nested loop is used to take input for each element of the first matrix. Each element is appended to the corresponding row, and the row is then appended to matrix1.

Step 4: Input Elements for the Second Matrix

  • The process is repeated to take input for the second matrix, which is stored in matrix2.

Step 5: Initialize the Resultant Matrix with Zeros

  • A new matrix result_matrix is initialized with zeros. This matrix will store the sum of matrix1 and matrix2.

Step 6: Add the Two Matrices

  • A nested loop is used to add corresponding elements of matrix1 and matrix2, and the result is stored in result_matrix.

Step 7: Display the Resulting Matrix

  • The resulting matrix is displayed using a nested loop, with each row printed on a new line.

Output Example

Example Output:

Enter the number of rows: 2
Enter the number of columns: 3
Enter the elements of the first matrix:
Element at position (1, 1): 1
Element at position (1, 2): 2
Element at position (1, 3): 3
Element at position (2, 1): 4
Element at position (2, 2): 5
Element at position (2, 3): 6
Enter the elements of the second matrix:
Element at position (1, 1): 7
Element at position (1, 2): 8
Element at position (1, 3): 9
Element at position (2, 1): 1
Element at position (2, 2): 2
Element at position (2, 3): 3

The resultant matrix after addition is:
8 10 12 
5 7 9 

Additional Examples

Example 1: Adding Two 3×3 Matrices

# Example of adding two 3x3 matrices
rows = 3
columns = 3
matrix1 = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
matrix2 = [
    [9, 8, 7],
    [6, 5, 4],
    [3, 2, 1]
]

# Resultant matrix initialization
result_matrix = [[0 for _ in range(columns)] for _ in range(rows)]

# Adding matrices
for i in range(rows):
    for j in range(columns):
        result_matrix[i][j] = matrix1[i][j] + matrix2[i][j]

# Displaying the resultant matrix
print("\nThe resultant 3x3 matrix after addition is:")
for row in result_matrix:
    for element in row:
        print(element, end=" ")
    print()

Output:

The resultant 3x3 matrix after addition is:
10 10 10 
10 10 10 
10 10 10 

Example 2: Adding Two Matrices with Negative and Positive Numbers

# Example with negative and positive numbers
matrix1 = [
    [-1, 2],
    [3, -4]
]
matrix2 = [
    [5, -6],
    [-7, 8]
]

rows = 2
columns = 2
result_matrix = [[0 for _ in range(columns)] for _ in range(rows)]

# Adding matrices
for i in range(rows):
    for j in range(columns):
        result_matrix[i][j] = matrix1[i][j] + matrix2[i][j]

# Displaying the resultant matrix
print("\nThe resultant matrix is:")
for row in result_matrix:
    for element in row:
        print(element, end=" ")
    print()

Output:

The resultant matrix is:
4 -4 
-4 4 

Conclusion

This Python program demonstrates how to add two matrices by taking input from the user for each matrix’s elements. The program then adds the corresponding elements of the two matrices and displays the resulting matrix. Understanding matrix addition is fundamental for performing operations in linear algebra and various computational tasks in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top