[英]Rotation of an array of vectors by an array of rotation matrices
If we have a 3 x 3
rotation matrix R
, it can be multiplied with v
, a 3 x N
array - an array of N
column vectors - to produce a new 3 x N
array of rotated vectors, like this: 如果我们有一个
3 x 3
旋转矩阵R
,可以将其与v
乘以一个3 x N
的数组N
列向量的数组-产生一个新的3 x N
的旋转向量数组,如下所示:
v_rotated = R.dot(v)
Now suppose we have a N x M x 3
array, N
times M
vectors, which I want to rotate with N
different 3 x 3
rotation matrices (one rotation matrix for each "row" of vectors). 现在假设我们有一个
N x M x 3
数组, N
M
向量,我想用N
不同的3 x 3
旋转矩阵(每个“行”向量一个旋转矩阵)旋转。 This is straightforward to do with a loop, but is there a faster and more compact (vectorized) way to do it, eg with numpy
's dot
or tensorproduct
? 这与循环很直接,但是有没有更快,更紧凑(矢量化)的方法来实现,例如使用
numpy
的dot
或张量tensorproduct
?
Example code for loop implementation: 循环实现的示例代码:
from numpy import cos, sin, array, pi, linspace, random
# 100 different rotation matrices:
R = [array([[1, 0, 0], [0, cos(theta), -sin(theta)], [0, sin(theta), cos(theta)]]) for theta in linspace(0, pi, 100)]
# 100 x 200 random vectors:
v = random.random((100, 200, 3))
# rotate vectors in loop:
rotated_v = array([R_.dot(v_.T).T for R_, v_ in zip(R, v)])
let's assume that v.shape
is (N, M, 3)
and R.shape
is (N, 3, 3)
, you can use np.einsum
假设
v.shape
为(N, M, 3)
并且R.shape
为(N, 3, 3)
,则可以使用np.einsum
import numpy as np
rotated_v = np.einsum('lij, lkj->lki', R, v)
where l
is the index on N
, i
and j
are the indexes on 3x3
rotation dimension, and k
is the index on M
. 其中
l
是N
的索引, i
和j
是3x3
旋转尺寸的索引, k
是M
的索引。
I matched my result with your as follow: 我将您的结果与您的匹配如下:
>>> print np.allclose(my_rotated_v, your_rotated_v)
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.