Introduction
Subtracting two matrices in NumPy is a pretty common task to perform. The most straightforward way to subtract two matrices in NumPy is by using the -
operator, which is the simplification of the np.subtract()
method - NumPy specific method designed for subtracting arrays and other array-like objects such as matrices.
Note: The array-like object in NumPy is considered to be any object which can be passed to the np.array()
method so that it creates an object that has the ndarray
type.
In this guide, you'll find out how to subtract two matrices in NumPy using both -
operator and np.subtract()
method, when to use either of them, and have a deeper understanding of all the nuances of the np.subtract()
method in NumPy.
How to Subtract Two Matrices in NumPy
In algebra, two matrices can be subtracted only if both of them have the same number of rows and columns, meaning that they are of the same shape. Let's assume you have two matrices of the same shape that you want to subtract:
matrix1 = np.array([[2, 4, 0], [9, 1, 7]])
matrix2 = np.array([[2, 2, 1], [3, 5, 8]])
Note: Before calling any of NumPy's methods, such as the np.array()
method for the first time, you have to import the NumPy module in your project with import numpy as np
As you can see, two matrices are of the same shape, meaning that the matrix1.shape
is equal to matrix2.shape
- both are equal to (2, 3)
. This fact is crucial because both the -
operator and the np.subtract()
method won't behave as expected otherwise.
Note: The shape
property of any ndarray
object (an array or a matrix) stores the shape of that object in a form of (m, n)
, where m
represents the number of rows and n
represents the number of columns in a matrix.
Now you can subtract those two matrices using the -
operator:
resultMatrix = matrix1 - matrix2
As simple as that! This line is equal to the following line:
resultMatrix = np.subtract(matrix1, matrix2)
In both of those cases, the resultMatrix
will have exactly the same value, as expected:
[ 0 2 -1]
[ 6 -4 -1]
Subtracting Two Matrices of Different Shapes in NumPy
The previous section illustrated the most intuitive way of using the subtraction in NumPy. Rules of algebra state that you can subtract two matrices only if they are of the same shape, thus the previous section describes the only type of matrix subtraction that is mathematically valid.
However, the NumPy library allows the np.subtract()
method to work even if argument matrices are not of the same shape. It does so with help of a mechanism called broadcasting, which defines how NumPy treats arrays of different shapes during arithmetic operations. Ultimately, they're equalized shape-wise, and the usual subtraction takes place.
For example, let's take a look at the following two matrices:
rowMatrix = np.array([1, 2, 3])
columnMatrix = np.array([[1], [2], [3]])
Those matrices definitely have different shapes, rowMatrix.shape
is (1, 3)
, and columnMatrix.shape
is (3, 1)
. This could confuse you into thinking that you can't perform subtraction of them in NumPy, but that is definitely possible (albeit, indirectly, as they're automatically broadcast before subtraction):
resultMatrix = np.subtract(rowMatrix, columnMatrix)
Note: The resultMatrix
will have the exact same value if you use the -
operator instead of np.subtract()
method
The resultMatrix
will have the following value:
[ 0 1 2]
[-1 0 1]
[-2 -1 0]
Though, this result may look a bit counterintuitive, but let's use it to illustrate the mechanism of broadcasting in simple terms.
What is NumPy Broadcasting?
In order to subtract columnMatrix
from rowMatrix
both of them must be of the same shape. Since those two matrices do not meet the mentioned criterion, the broadcasting mechanism comes in place. It makes sure to stretch both of them to have compatible shapes. Therefore, the rowMatrix
is stretched so that it forms the matrix of the shape (3, 3)
:
> Original `resultMatrix`:
[1 2 3]
> Broadcasted `resultMatrix`:
[1 2 3]
[1 2 3]
[1 2 3]
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
In a similar manner, the columnMatrix
is stretched to form the (3, 3)
matrix as well:
> Original `resultMatrix`:
[1]
[2]
[3]
> Broadcasted `resultMatrix`:
[1 1 1]
[2 2 2]
[3 3 3]
Now that you have two modified matrices of the same shape, the subtraction can be performed on them. The resulting matrix is the same as the resultMatrix
from the example above.
[1 2 3] [1 1 1] [ 0 1 2]
[1 2 3] - [2 2 2] = [-1 0 1]
[1 2 3] [3 3 3] [-2 -1 0]
Alert: Broadcasting is a far more complex mechanism than described here, so we strongly advise you to use it with caution or perform further research on the topic. For example, some other combination of two matrix shapes will produce a ValueError
because those shapes can't be broadcast into the same shape.
When to Use np.subtract() Method Instead of - Operator
Based on what you've seen until now, you can conclude that you can use both -
and subtract()
interchangeably pretty much any time you want. That's almost true, but there are some cases where you should consider using the np.subtract()
method instead of the -
operator.
In essence, the -
operator is an abstraction of the np.subtract()
method. When called, the -
operator will, effectively, call the np.subtract()
with its default parameters. Therefore, the one use case where you can consider using the np.subtract()
over the -
operator is when you want to tweak the predefined default behavior of the subtraction in the NumPy. We'll take a look at a few arguments that can be interesting to play around with.
Firstly, let's take a look at the declaration of thenp.subtract()
method:
numpy.subtract(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'subtract'>
Besides a few usual and self-explanatory arguments, the section of the declaration that will most probably draw your attention is <ufunc 'subtract'>
, so let's first clarify what it stands for. In NumPy, ufunc
stands for universal function, thus this argument signalizes that the np.subtract()
method is a universal function.
Universal functions in NumPy operate on arrays (more specifically ndarrays
) in an element-by-element fashion. They can efficiently iterate over elements of two ndarrays
and perform a predefined operation on corresponding elements. For example, np.subtract()
will subtract two corresponding elements from two ndarrays
. Therefore, you can think of universal functions as basic, predefined functions, which enable you to perform a wide variety of basic mathematical operations on ndarrays
.
Now we can describe some other interesting arguments:
x1
(required)- the first input array (or other array-like objects)
- has to be either the same shape as
x2
or broadcastable to the same shape asx2
x2
(required)- the second input array (or other array-like objects)
- has to be either the same shape as
x1
or broadcastable to the same shape asx1
out
(optional)- used if you want to specify the location where to store the result
- if not specified, the new object is created to store the result
- if specified, it has to be a
ndarray
object or a tuple ofndarray
andNone
objects - the specified object has to have the shape that the two input arrays broadcast to
where
(optional)- used if you want to specify some elements of the input array on which the
ufunc
will not be performed - the default value is
True
, thus thenp.subtract()
will subtract all corresponding elements fromx1
andx2
- if you want not to subtract elements on a certain position in the
out
array, you can pass the array of Boolean values which has the same shape as theout
array, and set the value toFalse
on those positions
- used if you want to specify some elements of the input array on which the
dtype
(optional)- used to specify the type of the result matrix
- by default, it is equal to the type of the input arrays
Conclusion
Whether you were looking for an easy way to subtract two matrices using NumPy or trying to recall more advanced concepts surrounding the np.subtract()
method, this guide has you covered. The main point of this guide was to give you the answer to both of those questions.
Firstly, we've covered the easy and intuitive way to subtract two matrices in the NumPy module. Alongside that, we've discussed the similarities and differences between the -
operator and the np.subtract()
method. Afterward, we've illustrated the concept of broadcasting in NumPy, but we do advise you to dig deeper on the subject of broadcasting.
In the end, we've given you a detailed overview of the np.subtract()
method in NumPy, thus you can tweak its default behavior to make it more suitable for certain more specific use cases.