Reputation: 1539
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.
Upvotes: 1
Views: 992
Reputation: 53029
Just a matter of broadcasting:
>>> D = np.cross(A[:, None, :], B)
>>> np.all(D==C)
True
Upvotes: 3