What is the best way to take the cross product of each corresponding row between two arrays? For example:
a = 20x3 array
b = 20x3 array
c = 20x3 array = some_cross_function(a, b) where:
c[0] = np.cross(a[0], b[0])
c[1] = np.cross(a[1], b[1])
c[2] = np.cross(a[2], b[2])
...etc...
I know this can be done with a simple python loop or using numpy's apply_along_axis, but I'm wondering if there is any good way to do this entirely within the underlying C code of numpy. I currently use a simple loop, but this is by far the slowest part of my code (my actual arrays are tens of thousands of rows long).
To compute the cross product of two vectors, use the numpy. cross() method in Python Numpy. The method returns c, the Vector cross product(s).
import numpy as np #calculate cross product of vectors A and B np. cross(A, B) #define function to calculate cross product def cross_prod(a, b): result = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return result #calculate cross product cross_prod(A, B)
Step 1: Import numpy. Step 2: Define two numpy arrays. Step 3: Find intersection between the arrays using the numpy. intersect1d() function.
Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray. all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent.
I'm probably going to have to delete this answer in a few minutes when I realize my mistake, but doesn't the obvious thing work?
>>> a = np.random.random((20,3))
>>> b = np.random.random((20,3))
>>> c = np.cross(a,b)
>>> c[0], np.cross(a[0], b[0])
(array([-0.02469147, 0.52341148, -0.65514102]), array([-0.02469147, 0.52341148, -0.65514102]))
>>> c[1], np.cross(a[1], b[1])
(array([-0.0733347 , -0.32691093, 0.40987079]), array([-0.0733347 , -0.32691093, 0.40987079]))
>>> all((c[i] == np.cross(a[i], b[i])).all() for i in range(len(c)))
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With