So I have a n x d
matrix and an n x 1
vector. I'm trying to write a code to subtract every row in the matrix by the vector.
I currently have a for
loop that iterates through and subtracts the i
-th row in the matrix by the vector. Is there a way to simply subtract an entire matrix by the vector?
Thanks!
Current code:
for i in xrange( len( X1 ) ): X[i,:] = X1[i,:] - X2
This is where X1
is the matrix's i
-th row and X2
is vector. Can I make it so that I don't need a for
loop?
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.
subtract() in Python. numpy. subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise.
When 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.
That works in numpy
but only if the trailing axes have the same dimension. Here is an example of successfully subtracting a vector from a matrix:
In [27]: print m; m.shape [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] Out[27]: (4, 3) In [28]: print v; v.shape [0 1 2] Out[28]: (3,) In [29]: m - v Out[29]: array([[0, 0, 0], [3, 3, 3], [6, 6, 6], [9, 9, 9]])
This worked because the trailing axis of both had the same dimension (3).
In your case, the leading axes had the same dimension. Here is an example, using the same v
as above, of how that can be fixed:
In [35]: print m; m.shape [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Out[35]: (3, 4) In [36]: (m.transpose() - v).transpose() Out[36]: array([[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9]])
The rules for broadcasting axes are explained in depth here.
In addition to @John1024 answer, "transposing" a one-dimensional vector in numpy can be done like this:
In [1]: v = np.arange(3) In [2]: v Out[2]: array([0, 1, 2]) In [3]: v = v[:, np.newaxis] In [4]: v Out[4]: array([[0], [1], [2]])
From here, subtracting v
from every column of m
is trivial using broadcasting:
In [5]: print(m) [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] In [6]: m - v Out[6]: array([[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9]])
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