Element wise cross product of vectors contained in 2 arrays with Python

荒凉一梦 提交于 2021-01-28 08:15:55

问题


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.


回答1:


Just a matter of broadcasting:

>>> D = np.cross(A[:, None, :], B)
>>> np.all(D==C)
True


来源:https://stackoverflow.com/questions/49931993/element-wise-cross-product-of-vectors-contained-in-2-arrays-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!