问题描述
所以我有一个 n x d
矩阵和一个 n x 1
向量.我正在尝试编写一个代码,用向量减去矩阵中的每一行.
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.
我目前有一个 for
循环,它遍历并减去矩阵中的 i
-th 行由向量.有没有办法简单地用向量减去整个矩阵?
谢谢!
当前代码:
for i in xrange( len( X1 ) ):
X[i,:] = X1[i,:] - X2
这里 X1
是矩阵的 i
-th 行和 X2
是向量.我可以让它不需要 for
循环吗?
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?
推荐答案
这在 numpy
中有效,但仅当尾随轴具有相同尺寸时.下面是一个从矩阵中成功减去向量的例子:
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]])
这是可行的,因为两者的尾随轴具有相同的维度 (3).
This worked because the trailing axis of both had the same dimension (3).
在您的情况下,引导轴具有相同的尺寸.这是一个使用与上述相同的 v
的示例,说明如何解决此问题:
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.
这篇关于numpy 用向量减去矩阵的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!