[英]methods that return cross product of two 3xN arrays (e.g. time-dependent vectors)
I have two vectors evaluated at say 10,000 points as two [3, 10000]
arrays. 我有两个向量,它们在10,000个点处被评估为两个
[3, 10000]
数组。 Reading the definitions for np.cross
and np.einsum
I don't understand how to use them without a loop to get the cross product here. 阅读
np.cross
和np.einsum
的定义,我不明白如何在没有循环的情况下使用它们来获得叉积。
This is what I do now, just hard-wired arrays. 这就是我现在要做的,只是硬接线阵列。 Can either of those, or anything else within the
numpy
or scipy
universe do this as fast? numpy
或scipy
宇宙中的任何一个,或其他任何事物, scipy
做到这一点? I'm thinking that it would be nicer to use something standard like np.cross
or np.einsum
even if it's the same speed as my method, but I don't see how without looping. 我在想,即使使用与我的方法相同的速度,也最好使用
np.cross
或np.einsum
类的标准,但是我不知道如何避免循环。
def cross_these(a, b):
c0 = a[1]*b[2] - a[2]*b[1]
c1 = a[2]*b[0] - a[0]*b[2]
c2 = a[0]*b[1] - a[1]*b[0]
return np.vstack((c0, c1, c2))
You need the optional keyword arguments to np.cross
that specify which axes of the input (and possibly output) arrays correspond to Cartesian coordinates, and you're done: 您需要
np.cross
的可选关键字参数来指定输入(可能是输出)数组的哪些轴对应于笛卡尔坐标,然后完成:
import numpy as np
a = np.random.rand(3,5)
b = np.random.rand(3,5)
c = np.cross(a, b, axisa=0, axisb=0, axisc=0)
# check if each row is equal to the simple cross-product
all(np.allclose(np.cross(a,b,axisa=0,axisb=0)[k],
np.cross(a[:,k],b[:,k])) for k in range(a.shape[1]))
Here's a vectorized approach - 这是向量化方法-
d0 = np.array([[1,2,0],[2,0,1]]) # Scaling values
d1 = np.array([[2,0,1],[1,2,0]])
out = a[d0[0]]*b[d1[0]] - a[d0[1]]*b[d1[1]]
As one-liner - 作为单线-
a[[1,2,0]]*b[[2,0,1]] - a[[2,0,1]]*b[[1,2,0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.