包含在 2 个数组中的向量的元素交叉乘积与 Python [英] Element wise cross product of vectors contained in 2 arrays with Python
问题描述
我有两个数组,一个包含向量列表(A
),一个包含向量的二维列表(B
).我正在寻找以特定方式对每个数组中的向量进行元素明智的叉积.
A
中的第一个向量应该与 B
的第一个元素中包含的所有 3 个向量进行交叉积(?).
这是一个最小的例子:
将 numpy 导入为 npA = np.random.rand(2,3)B = np.random.rand(2,3,3)C = np.random.rand(2,3,3)C[0,0] = np.cross(A[0],B[0,0])C[0,1] = np.cross(A[0],B[0,1])C[0,2] = np.cross(A[0],B[0,2])C[1,0] = np.cross(A[1],B[1,0])C[1,1] = np.cross(A[1],B[1,1])C[1,2] = np.cross(A[1],B[1,2])
为了提高效率,我想避免使用 for
循环.
我使用以下方法对点积进行了相同的操作:
C = np.einsum('aj,ijk->ij',A,B)
但我似乎无法对交叉产品做同样的事情.
只是广播的问题:
<预><代码>>>>D = np.cross(A[:, None, :], B)>>>np.all(D==C)真的I have two arrays, one containing a list of vectors (A
) and one containing a 2D list of vectors (B
). I am looking to do an element wise cross product of the vectors in each array in a specific way.
The fist vector in A
should be cross producted (?) by all 3 vectors contained in the first element of B
.
Here is a minimal example:
import numpy as np
A = np.random.rand(2,3)
B = np.random.rand(2,3,3)
C = np.random.rand(2,3,3)
C[0,0] = np.cross(A[0],B[0,0])
C[0,1] = np.cross(A[0],B[0,1])
C[0,2] = np.cross(A[0],B[0,2])
C[1,0] = np.cross(A[1],B[1,0])
C[1,1] = np.cross(A[1],B[1,1])
C[1,2] = np.cross(A[1],B[1,2])
I would like to avoid using for
loops for efficiency.
I managed doing the same with the dot product by using:
C = np.einsum('aj,ijk->ij',A,B)
But I cant seem to be able to do the same with the cross product.
Just a matter of broadcasting:
>>> D = np.cross(A[:, None, :], B)
>>> np.all(D==C)
True
这篇关于包含在 2 个数组中的向量的元素交叉乘积与 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!