[英]Is there a vectorized way to apply a transformation matrix to a group of vectors?
Imagine you have a group of vectors, eg in the form of a trajectory.想象一下,您有一组向量,例如以轨迹的形式。 Is there a vectorized way of applying the transformation matrix to all data points at once, or are you stuck with a for-loop?是否有一种将变换矩阵一次应用于所有数据点的矢量化方式,或者您是否陷入了 for 循环? Here is some sample code:这是一些示例代码:
import numpy as np
angle = np.deg2rad(90)
rotM = np.array(
[
[np.cos(angle), -np.sin(angle), 0],
[np.sin(angle), np.cos(angle), 0],
[ 0, 0, 1],
]
)
# trajectory with columns t, x, y, z
trajectory = np.array(
[
[1, 1, 0, 0],
[2, 2, 1, 0],
[3, 3, 2, 0],
[4, 4, 3, 1],
[5, 6, 4, 2],
[6, 9, 5, 3],
]
)
# transform coordinates
for i in range(len(trajectory)):
trajectory[i][1:] = np.dot(rotM, trajectory[i][1:])
All I found so far is numpy.linalg.multi_dot
, and these two posts ( one , two ), none of which seem to apply to my case.到目前为止,我发现的只是numpy.linalg.multi_dot
和这两个帖子( one , two ),似乎都不适用于我的情况。
For this case, use broadcasting along with np.matmul
/ @
.对于这种情况,将广播与np.matmul
/ @
一起使用。 You can multiply a 3x3 martrix by an Nx3x1 array of vectors:您可以将 3x3 矩阵乘以 Nx3x1 向量数组:
trajectory[:, 1:] = rotM @ trajectory[:, 1:, None]
A cleaner and more flexible solution might be to use scipy.spatial.transform.Rotation
objects instead of hand-crafting the matrix yourself:更清洁和更灵活的解决方案可能是使用scipy.spatial.transform.Rotation
对象,而不是自己手工制作矩阵:
rotM = Rotation.from_euler('z', angle)
trajectory[:, 1:] = rotM.apply(trajectory[:, 1:])
No need to add shim dimensions in this case.在这种情况下无需添加垫片尺寸。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.