如何在没有 for 循环的情况下按元素乘以 numpy 矩阵?

How can I multiply numpy matrix elementwise without for loops?

我想将相同的矩阵 (3x3) 应用于向量中包含的大量点。矢量的形式为 (40000 x 3)。下面的代码完成了这项工作,但它太慢了。我可以使用任何 numpy 技巧来消除 for 循环和追加函数吗?

def apply_matrix_to_shape(Matrix,Points):
    """input a desired transformation and an array of points that are in 
    the format np.array([[x1,y1,z1],[x2,y2,z2],...,]]).   will output
    a new array of translated points with the same format"""
    New_shape = np.array([])
    M = Matrix
    for p in Points:
        New_shape = np.append(New_shape,[p[0]*M[0][0]+p[1]*M[0][1]+p[2]*M[0][2],
                                p[0]*M[1][0]+p[1]*M[1][1]+p[2]*M[1][2],
                                p[0]*M[2][0]+p[1]*M[2][1]+p[2]*M[2][2]])
    Rows = int(len(New_shape) / 3)
    return np.reshape(New_shape,(Rows,3))

你基本上想要两个数组的matrix multiplication不是元素方面的)。您只需要转置使形状对齐,然后转回结果:

m.dot(p.T).T

或等效地:

(m@p.T).T

m = np.random.random((3,3))
p = np.random.random((15,3))
np.allclose((m@p.T).T, apply_matrix_to_shape(m, p))
# True

确实,我认为您想要的是 NumPy 上线的主要原因之一。您可以使用点积函数和转置函数(只需 .T 或 .transpose())

import numpy as np

points = np.array([[1, 2, 3],
                   [4, 5, 6]])

T_matrix = np.array([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])


result = points.dot(T_matrix.T)

print(result)


>>>  [[ 14  32  50]
     [ 32  77 122]]