Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Matrix Subtraction Confusion

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!

like image 566
astromax Avatar asked Apr 03 '13 19:04

astromax


People also ask

How do you subtract a NumPy Matrix?

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.

Can you subtract two NumPy arrays?

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.

How do you subtract two 2d arrays in Python?

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.

How do you subtract two matrices in Python?

subtract() to subtract elements of two matrices. It returns the difference of arr1 and arr2, element-wise.


1 Answers

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.

like image 96
kith Avatar answered Oct 16 '22 06:10

kith