有没有一种有效的方法可以将许多不同的旋转矩阵乘以同一个向量?
现在我正在执行以下操作,程序极其缓慢
for i, rm in enumerate(ray_rotation_matrices):
scan_point = rm * np.vstack([scale, 0, 0, 1])
scan_points[i] = np.hstack(scan_point[:3])
每个rm
是用于同质坐标的4x4
矩阵。我可以以某种方式广播,但我如何确保它应用矩阵乘法而不是元素明智的产品?
我想摆脱for循环......
答案 0 :(得分:3)
使用一个大的array
和矩阵乘法运算符@
。它是开箱即用的矢量化。例如:
# a stack of five 4x4 matrices
>>> m = np.random.random((5, 4, 4))
>>> v = np.random.random((4,))
# all five matrix vector products in one go
>>> m@v
array([[1.08929927, 0.98770373, 1.0470138 , 1.266117 ],
[0.71691193, 0.68655178, 1.25601832, 1.22123406],
[1.3964922 , 1.02123137, 1.03709715, 0.72414757],
[0.9422159 , 0.84904553, 0.8506686 , 1.29374861],
[1.02159382, 1.36399314, 1.06503775, 0.56242674]])
# doing it one-by-one gives the same answer
>>> [mi@v for mi in m]
[array([1.08929927, 0.98770373, 1.0470138 , 1.266117 ]), array([0.71691193, 0.68655178, 1.25601832, 1.22123406]), array([1.3964922 , 1.02123137, 1.03709715, 0.72414757]), array([0.9422159 , 0.84904553, 0.8506686 , 1.29374861]), array([1.02159382, 1.36399314, 1.06503775, 0.56242674])]