I have a question about the result of an operation I accidentally performed with two numpy matrices (and later fixed).
Let's say that I have a column vector, A = [1,2,3], and a row vector B = [1,1,1]. As far as I know there is no correct mathematical way to "subtract" these two vectors, i.e. this should be an undefined operation. And yet, when I do so, I get back:
>>> matrix([[0, 1, 2],
[0, 1, 2],
[0, 1, 2]])
I thought that this might be some sort of broadcasting operation, but this still troubles me a bit. Shouldn't numpy.matrix objects only contain mathematically valid matrix operations?
Any help is appreciated!
Thanks!
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.
A Quick Introduction to Numpy SubtractWhen you use np. subtract on two same-sized Numpy arrays, the function will subtract the elements of the second array from the elements of the first array. It performs this subtraction in an “element-wise” fashion.
subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise. Parameters : arr1 : [array_like or scalar]1st Input array. arr2 : [array_like or scalar]2nd Input array.
subtract() to subtract elements of two matrices. It returns the difference of arr1 and arr2, element-wise.
A and B are being broadcasted together:
A = np.matrix([[1],[2],[3]])
#a 3x1 vector
#1
#2
#3
B = np.matrix([[1,1,1]])
#a 1x3 vector
#1 1 1
A-B
#a 3x3 vector
#0 0 0
#1 1 1
#2 2 2
A gets broadcasted along its size 1 dimension(columns) into
#1 1 1
#2 2 2
#3 3 3
B get broadcasted along its size 1 dimension(rows) into
#1 1 1
#1 1 1
#1 1 1
Then A-B is computed as usual for two 3x3 matrices.
If you want to know why it does this instead of reporting an error it's because np.matrix inherits from np.array. np.matrix overrides multiplication, but not addition and subtraction, so it uses the operations based on the np.array, which broadcasts when the dimensions allow it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With