Python Program to Subtract Two Matrices

Introduction

Matrix subtraction is a basic operation in linear algebra, where two matrices of the same dimensions are subtracted element-wise. This tutorial will guide you through creating a Python program that subtracts one matrix from another.

Example:

  • Matrix 1:

    5 6 7
    8 9 10
    
  • Matrix 2:

    1 2 3
    4 5 6
    
  • Resultant Matrix:

    4 4 4
    4 4 4
    

Problem Statement

Create a Python program that:

  • Takes two matrices as input.
  • Checks if the matrices have the same dimensions.
  • Subtracts the second matrix from the first matrix 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. Subtract the Matrices: Use nested loops to subtract 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 Subtract 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: Subtract the second matrix from the first matrix
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 subtraction 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 difference between matrix1 and matrix2.

Step 6: Subtract the Second Matrix from the First Matrix

  • A nested loop is used to subtract corresponding elements of matrix2 from matrix1, 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): 5
Element at position (1, 2): 6
Element at position (1, 3): 7
Element at position (2, 1): 8
Element at position (2, 2): 9
Element at position (2, 3): 10
Enter the elements of the second 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

The resultant matrix after subtraction is:
4 4 4 
4 4 4 

Additional Examples

Example 1: Subtracting Two 3×3 Matrices

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

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

# Subtracting 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 subtraction is:")
for row in result_matrix:
    for element in row:
        print(element, end=" ")
    print()

Output:

The resultant 3x3 matrix after subtraction is:
8 6 4 
2 0 -2 
-4 -6 -8 

Example 2: Subtracting Two Matrices with Negative and Positive Numbers

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

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

# Subtracting 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:
3 4 
-7 1 

Conclusion

This Python program demonstrates how to subtract two matrices by taking input from the user for each matrix’s elements. The program then subtracts the corresponding elements of the second matrix from the first matrix and displays the resulting matrix. Understanding matrix subtraction 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