Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...