We can use NumPy to perform addition and subtraction in vectors and matrices using a single line of code.
Import the library:
import numpy as np
Perform addition of two square matrices:
# Given two arrays
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
matrix2 = np.array([[1, 3, 5], [2, 4, 6], [7, 9, 11], [8, 10, 12]])
print("Matrix 1 adds up to Matrix 2:\\n", np.add(matrix1, matrix2))
Output:
Matrix 1 adds up to Matrix 2:
[[ 2 5 8]
[ 6 9 12]
[14 17 20]
[18 21 24]]
Perform subtraction of two square matrices:
# Given two arrays
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
matrix2 = np.array([[1, 3, 5], [2, 4, 6], [7, 9, 11], [8, 10, 12]])
print("Matrix 1 subtracts to Matrix 2:\\n", np.subtract(matrix1, matrix2))
Output:
Matrix 1 subtracts to Matrix 2:
[[ 0 -1 -2]
[ 2 1 0]
[ 0 -1 -2]
[ 2 1 0]]
The following code also returns the same results as the preceding code:
# Given two arrays matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) matrix2 = np.array([[1, 3, 5], [2, 4, 6], [7, 9, 11], [8, 10, 12]]) # These functions are also the same as np.add() and np.subtract() print("Matrix 1 + Matrix 2:\\n", matrix1 + matrix2) print("Matrix 1 - Matrix 2:\\n", matrix1 - matrix2)Output:
Matrix 1 + Matrix 2: [[ 2 5 8] [ 6 9 12] [14 17 20] [18 21 24]] Matrix 1 - Matrix 2: [[ 0 -1 -2] [ 2 1 0] [ 0 -1 -2] [ 2 1 0]]
Nested Calculations: You can also add and subtract multiple matrices at the same time.