计算两组向量numpy之间的叉积的有效方法 [英] Efficient way of computing the cross products between two sets of vectors numpy
问题描述
我分别有两组2000个3D矢量,并且我需要计算每个可能的对之间的叉积.我目前是这样的
I have two sets of 2000 3D vectors each, and I need to compute the cross product between each possible pair. I currently do it like this
for tx in tangents_x:
for ty in tangents_y:
cross = np.cross(tx, ty)
(... do something with the cross variable...)
这有效,但是速度很慢.有没有办法使其更快?
This works, but it's pretty slow. Is there a way to make it faster?
如果我对基于元素的产品感兴趣,我可以做以下事情
If I was interested in the element-wise product, I could just do the following
# Define initial vectors
tx = np.array([np.random.randn(3) for i in range(2000)])
ty = np.array([np.random.randn(3) for i in range(2000)])
# Store them into matrices
X = np.array([tx for i in range(2000)])
Y = np.array([ty for i in range(2000)]).T
# Compute the element-wise product
ew = X * Y
# Use the element_wise product as usual
for i,tx in enumerate(tangents_x):
for j,ty in enumerate(tangents_y):
(... use the element wise product of tx and ty as ew[i,j])
如何将其应用到叉积而不是按元素的积?或者,您是否看到另一种选择?
How can I apply this to the cross product instead of the element-wise one? Or, do you see another alternative?
非常感谢:)
推荐答案
就像许多numpy函数cross
支持广播一样,因此您可以轻松地做到:
Like many numpy functions cross
supports broadcasting, therefore you can simply do:
np.cross(tangents_x[:, None, :], tangents_y)
或-更详细,但可能更容易阅读
or - more verbose but maybe easier to read
np.cross(tangents_x[:, None, :], tangents_y[None, :, :])
这会将tangents_x
和tangents_y
重塑为形状2000, 1, 3
和1, 2000, 3
.根据广播规则,这将被解释为两个形状为2000, 2000, 3
的数组,其中tangents_x
沿轴1
重复,而tangents_y
沿轴0
重复.
This reshapes tangents_x
and tangents_y
to shapes 2000, 1, 3
and 1, 2000, 3
. By the rules of broadcasting this will be interpreted like two arrays of shape 2000, 2000, 3
where tangents_x
is repeated along axis 1
and tangents_y
is repeated along axis 0
.
这篇关于计算两组向量numpy之间的叉积的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!