简体   繁体   English

Numpy 用一个向量数组点一个矩阵,得到一个新的向量数组

[英]Numpy dot one matrix with an array of vectors and get a new array of vectors

Say we have an array of 2D vectors (describing a square shape), and a matrix (scale along y axis):假设我们有一个二维向量数组(描述一个正方形)和一个矩阵(沿 y 轴缩放):

vecs = np.array([[1, 0],
                 [1, 1],
                 [0, 1],
                 [0, 0]])
mat = np.array([[1, 0],
                [0, 2]])

I want to get a new array of vectors, where each vector from vecs is dot multiplied with mat .我想得到一个新的向量数组,其中来自vecs的每个向量都与mat相乘。 Now I do it like this:现在我这样做:

new_vecs = vecs.copy()
for i, vec in enumerate(vecs):
    new_vecs[i] = np.dot(mat, vec)

This produces the desired result:这会产生所需的结果:

>>> print(new_vecs)
[[1 0]
 [1 2]
 [0 2]
 [0 0]]

What are better ways to do this?有什么更好的方法来做到这一点?

The dot product np.dot will multiply matrices of any shape with each other, as long as their shapes line up: np.dot((a,b), (b,c)) -> (a,c) . 点积np.dot将将任意形状的矩阵彼此相乘,只要它们的形状np.dot((a,b), (b,c)) -> (a,c)np.dot((a,b), (b,c)) -> (a,c) So if you invert the order, Numpy does this for you in one call: 因此,如果您颠倒订单,Numpy会在一个电话中为您完成此操作:

In [3]: np.dot(vecs, mat)
Out[3]:
array([[1, 0],
       [1, 2],
       [0, 2],
       [0, 0]])

You can use the following:您可以使用以下内容:

np.dot(mat , vecs.T).T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM