如何从角度矢量矢量化 N 旋转矩阵的创建?
How to vectorize the creation of N rotation matrix from a vector of angles?
数据:
theta是N个角的向量。
问题:如何在向量化时从theta创建一个N个二维旋转矩阵向量?
如果不进行矢量化,我可以想到一个 for 循环:
import numpy as np
N = 100
theta = np.random.rand(N)*2*np.pi
def R(theta_v):
Rotation = np.empty((len(theta_v), 2, 2))
for k, theta in enumerate(theta_v):
Rotation[k] = np.array([ [np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)] ])
return Rotation
Rotation = R(theta)
有没有办法避免for loop
以获得更高效的代码?
您可以使用矢量化版本的 cos 和 sin 来矢量化您的函数,然后重新排列结果:
def R_vec(theta):
c, s = np.cos(theta), np.sin(theta)
return np.array([c, -s, s, c]).T.reshape(len(theta),2,2)
对于 N=100,矢量化版本比我计算机上的原始版本快大约 110 倍。
数据: theta是N个角的向量。
问题:如何在向量化时从theta创建一个N个二维旋转矩阵向量?
如果不进行矢量化,我可以想到一个 for 循环:
import numpy as np
N = 100
theta = np.random.rand(N)*2*np.pi
def R(theta_v):
Rotation = np.empty((len(theta_v), 2, 2))
for k, theta in enumerate(theta_v):
Rotation[k] = np.array([ [np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)] ])
return Rotation
Rotation = R(theta)
有没有办法避免for loop
以获得更高效的代码?
您可以使用矢量化版本的 cos 和 sin 来矢量化您的函数,然后重新排列结果:
def R_vec(theta):
c, s = np.cos(theta), np.sin(theta)
return np.array([c, -s, s, c]).T.reshape(len(theta),2,2)
对于 N=100,矢量化版本比我计算机上的原始版本快大约 110 倍。