Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 558
Scott B Avatar asked Mar 25 '13 22:03

Scott B


People also ask

How do you cross product two arrays in Python?

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

How do you do cross multiplication in NumPy?

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)

How do you find the intersection of two arrays using NumPy?

Step 1: Import numpy. Step 2: Define two numpy arrays. Step 3: Find intersection between the arrays using the numpy. intersect1d() function.

How do I compare values in two NumPy arrays?

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.


1 Answers

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
like image 96
DSM Avatar answered Sep 22 '22 21:09

DSM