pythonnumpyarray-broadcastingcross-product

Element-wise Cross Product of 2D arrays of Coordinates


I'm working with a dataset that stores an array of unit-vectors as arrays of the vectors' components.

How would I use vectorised code / broadcasting to write clean and compact code to give the cross product of the vectors element-wise?

For example, here's a brute force method for looping through the length of the arrays, picking out the coordinates, re-composing the two vectors, then calculating the cross product.

x = [0,0,1,1]
y = [0,1,0,1]
z = [1,0,0,1]

v1 = np.array([x,y,z])

x = [1,1,0,1]
y = [1,0,1,1]
z = [0,1,1,1]

v2 = np.array([x,y,z])

result = []
for i in range(0, len(x)):
    a = [v1[0][i], v1[1][i], v1[2][i]]
    b = [v2[0][i], v2[1][i], v2[2][i]]
    result.append(np.cross(a,b))

result

>>>

[
 array([-1,  1,  0]),
 array([ 1,  0, -1]),
 array([ 0, -1,  1]),
 array([ 0,  0,  0])
]

I've tried to understand this question and answer to generalise it, but failed:
- Element wise cross product of vectors contained in 2 arrays with Python


Solution

  • np.cross can work with 2D arrays too, you just need to specify the right axes:

    np.cross(v1,v2, axisa=0, axisb=0)
    array([[-1,  1,  0],
           [ 1,  0, -1],
           [ 0, -1,  1],
           [ 0,  0,  0]])