Overview
- For subtracting one matrix from another matrix, the dimensions of both the matrices should be equal.
- Subtraction of two matrices is similar to adding two matrices.
- To subtract Matrix-B from Matrix-A, subtract each entry of Matrix-B from the corresponding entry of Matrix-A and place the result in the same position of the new matrix.
- The numpy.ndarray has __sub__() method which subtracts one ndarray object from another and returns the resultant ndarray object.
Example
# import numpy module
import numpy as np
# import python standard library module - random
import random
# Function to populate a matrix with random data
def FillMatrix(matrix_in):
for x in range(0, matrix_in.shape[0]):
for y in range(0, matrix_in.shape[1]):
matrix_in[x][y] = random.randrange(2, 10) + 2
# Create two 4x4 matrices using ndarray
matrix1 = np.ndarray((4,4))
matrix2 = np.ndarray((4,4))
# Fill the matrices i.e., the two dimensional arrays created using ndarray objects
FillMatrix(matrix1)
FillMatrix(matrix2)
# Add two matrices - two nd arrays
add_results = matrix1.__sub__(matrix2)
# Print Matrix1
print("Matrix1:")
print(matrix1)
# Print Matrix2
print("Matrix2:")
print(matrix2)
# Print the results of subtracting two matrices
print("Result of subtracting Matrix1 and Matrix2:")
print(add_results)Output
Matrix1:
[[ 5. 9. 5. 8.]
[ 4. 10. 11. 9.]
[ 9. 5. 6. 5.]
[ 10. 10. 10. 8.]]
Matrix2:
[[ 9. 10. 9. 4.]
[ 9. 6. 8. 4.]
[ 9. 11. 11. 4.]
[ 6. 4. 8. 11.]]
Result of subtracting Matrix1 and Matrix2:
[[-4. -1. -4. 4.]
[-5. 4. 3. 5.]
[ 0. -6. -5. 1.]
[ 4. 6. 2. -3.]]##