Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy subtract every row of matrix by vector

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?

like image 221
thehandyman Avatar asked Oct 13 '14 04:10

thehandyman


People also ask

How do you subtract a number from all elements of a NumPy array?

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.

How do you do element-wise subtraction in Python?

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.

How does NP subtract work?

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.


2 Answers

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.

like image 131
John1024 Avatar answered Oct 05 '22 12:10

John1024


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]]) 
like image 25
Nagasaki45 Avatar answered Oct 05 '22 11:10

Nagasaki45