Matrix Addition and Subtraction in Python

Matrix Addition & Subtraction in Python

Understanding element-wise matrix operations using standard Python lists

What are Matrix Addition and Subtraction?

In mathematics, a matrix is a two-dimensional grid of numbers arranged in rows and columns. When performing addition or subtraction on matrices, the operation is done element-wise. This means that each element in the first matrix is added to or subtracted from the corresponding element in the second matrix.

Important Requirement: To add or subtract two matrices, they must have the same dimensions (the same number of rows and the same number of columns). If matrix A is a 2x3 matrix, matrix B must also be a 2x3 matrix.

The Python Program

Below is a pure Python implementation that demonstrates both addition and subtraction using nested loops, avoiding external libraries like NumPy to show the core logic.

# This program performs element-wise addition and subtraction on two 2D matrices.

# Define two sample matrices of the same dimensions (3x3)
matrix_a = [
    [12, 7, 3],
    [4, 5, 6],
    [7, 8, 9]
]

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

# Get the number of rows and columns from matrix_a
rows = len(matrix_a)
cols = len(matrix_a[0])

# Initialize result matrices with zeros matching the dimensions
result_add = [[0 for _ in range(cols)] for _ in range(rows)]
result_sub = [[0 for _ in range(cols)] for _ in range(rows)]

# Iterate through each row of the matrices
for i in range(rows):
    # Iterate through each column of the current row
    for j in range(cols):
        # Add corresponding elements and store in the addition result matrix
        result_add[i][j] = matrix_a[i][j] + matrix_b[i][j]
        # Subtract corresponding elements and store in the subtraction result matrix
        result_sub[i][j] = matrix_a[i][j] - matrix_b[i][j]

# Display the results
print("Matrix Addition Result:")
for row in result_add:
    print(row)

print("\nMatrix Subtraction Result:")
for row in result_sub:
    print(row)

Sample Inputs & Outputs

Sample Inputs

Matrix A:
[12, 7, 3]
[4,  5, 6]
[7,  8, 9]
Matrix B:
[5, 8, 1]
[6, 7, 3]
[4, 5, 9]

Program Outputs

Addition Result (A + B):
[17, 15,  4]
[10, 12,  9]
[11, 13, 18]
Subtraction Result (A - B):
[ 7, -1,  2]
[-2, -2,  3]
[ 3,  3,  0]

Comments