Search code examples
pythonnumpycross-product

Python/Numpy - Cross Product of Matching Rows in Two Arrays


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).


Solution

  • 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