我有两组,每组 2000 个 3D 向量,我需要计算每个可能对之间的叉积。我目前这样做
for tx in tangents_x:
for ty in tangents_y:
cross = np.cross(tx, ty)
(... do something with the cross variable...)
这可行,但速度相当慢。有没有办法让它更快?
如果我对元素产品感兴趣,我可以执行以下操作
# 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])
如何将其应用于叉积而不是元素级积?或者,您看到另一种选择吗?
非常感谢 :)
像许多 numpy 函数一样cross
支持广播,因此你可以简单地执行以下操作:
np.cross(tangents_x[:, None, :], tangents_y)
或者 - 更详细但可能更容易阅读
np.cross(tangents_x[:, None, :], tangents_y[None, :, :])
这重塑了tangents_x
and tangents_y
形状2000, 1, 3
and 1, 2000, 3
。根据广播规则,这将被解释为两个形状数组2000, 2000, 3
where tangents_x
沿轴重复1
and tangents_y
沿轴重复0
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)