How To Add/Subtract With Numpy Matrices
Adding/Subtracting With Matrices
Adding and subtracting matrices is a fundamental part of linear algebra and a lot of data science techniques.
Let’s take a look at how to add/subtract with numpy arrays and matrices.
First, let’s import numpy and create some matrices to practice our operations with.
import numpy as np
a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
b = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
Now that we have matrices to play with, it only takes a single operation, with the help of numpy, to add or subtract our a and b matrices.
np.add(a,b)
# array([[ 2, 4, 6, 8],
# [10, 12, 14, 16],
# [18, 20, 22, 24],
# [26, 28, 30, 32]])
np.subtract(a,b)
#array([[0, 0, 0, 0],
# [0, 0, 0, 0],
# [0, 0, 0, 0],
# [0, 0, 0, 0]])
Adding and subtracting wasn’t so bad was it?
Check out the full code sample below.
import numpy as np
a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
b = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
np.add(a,b)
# array([[ 2, 4, 6, 8],
# [10, 12, 14, 16],
# [18, 20, 22, 24],
# [26, 28, 30, 32]])
np.subtract(a,b)
#array([[0, 0, 0, 0],
# [0, 0, 0, 0],
# [0, 0, 0, 0],
# [0, 0, 0, 0]])