Adding and Subtracting Matrices in Python
In this article, we will learn how to add and subtract matrices in Python using both NumPy (fast and simple) and nested loops (manual approach).
For Example:
Suppose we have two matrices A and B.
A = [[1,2],[3,4]]
B = [[4,5],[6,7]]
then we get
A+B = [[5,7],[9,11]] #Addition
A-B = [[-3,-3],[-3,-3]] #Subraction
Adding Matrices
NumPy provides the np.add() function, which adds two matrices element-wise.
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[4, 5], [6, 7]])
print("Matrix A:\n", A)
print("Matrix B:\n", B)
# Adding matrices
C = np.add(A, B)
print("Result:\n", C)
Output
Matrix A: [[1 2] [3 4]] Matrix B: [[4 5] [6 7]] Result: [[ 5 7] [ 9 11]]
Explanation: np.add(A, B) adds corresponding elements of matrices A and B and result is a new matrix C with element-wise sums.
Subtracting Matrices
NumPy also provides np.subtract(), which subtracts one matrix from another element-wise.
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[4, 5], [6, 7]])
print("Matrix A:\n", A)
print("Matrix B:\n", B)
# Subtracting matrices
C = np.subtract(A, B)
print("Result:\n", C)
Output
Matrix A: [[1 2] [3 4]] Matrix B: [[4 5] [6 7]] Result: [[-3 -3] [-3 -3]]
Explanation: np.subtract(A, B) subtracts each element of B from A and result is a matrix with the element-wise differences.
Adding and Subtracting Matrices using Nested Loops
This manual approach uses nested loops to perform both addition and subtraction of two matrices without using NumPy.
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[4, 5], [6, 7]]
print("Matrix 1:")
for row in matrix1:
print(row)
print("Matrix 2:")
for row in matrix2:
print(row)
add_result = [[0, 0], [0, 0]]
sub_result = [[0, 0], [0, 0]]
# Perform addition and subtraction
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
add_result[i][j] = matrix1[i][j] + matrix2[i][j]
sub_result[i][j] = matrix1[i][j] - matrix2[i][j]
print("Addition Result:")
for row in add_result:
print(row)
print("Subtraction Result:")
for row in sub_result:
print(row)
Output
Matrix 1: [1, 2] [3, 4] Matrix 2: [4, 5] [6, 7] Addition Result: [5, 7] [9, 11] Subtraction Result: [-3, -3] [-3, -3]
Explanation: We iterate over rows (i) and columns (j) using nested loops. At each index [i][j], we calculate both:
- add_result[i][j] = matrix1[i][j] + matrix2[i][j]
- sub_result[i][j] = matrix1[i][j] - matrix2[i][j]
- Finally, both results are printed row by row.