![]() |
VOOZH | about |
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
NumPy provides the np.add() function, which adds two matrices element-wise.
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.
NumPy also provides np.subtract(), which subtracts one matrix from another element-wise.
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.
This manual approach uses nested loops to perform both addition and subtraction of two matrices without using NumPy.
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: