## methods that return cross product of two 3xN arrays (e.g. time-dependent vectors)

Question

I have two vectors evaluated at say 10,000 points as two `[3, 10000]` arrays. Reading the definitions for `np.cross` and `np.einsum` I don't understand how to use them without a loop to get the cross product here.

This is what I do now, just hard-wired arrays. Can either of those, or anything else within the `numpy` or `scipy` universe do this as fast? I'm thinking that it would be nicer to use something standard like `np.cross` or `np.einsum` even if it's the same speed as my method, but I don't see how without looping.

``````def cross_these(a, b):

c0 = a[1]*b[2] - a[2]*b[1]
c1 = a[2]*b[0] - a[0]*b[2]
c2 = a[0]*b[1] - a[1]*b[0]

return np.vstack((c0, c1, c2))
``````

Show source

## Answers to methods that return cross product of two 3xN arrays (e.g. time-dependent vectors) ( 2 )

1. You need the optional keyword arguments to `np.cross` that specify which axes of the input (and possibly output) arrays correspond to Cartesian coordinates, and you're done:

``````import numpy as np
a = np.random.rand(3,5)
b = np.random.rand(3,5)
c = np.cross(a, b, axisa=0, axisb=0, axisc=0)

# check if each row is equal to the simple cross-product
all(np.allclose(np.cross(a,b,axisa=0,axisb=0)[k],
np.cross(a[:,k],b[:,k])) for k in range(a.shape[1]))
``````
2. Here's a vectorized approach -

``````d0 = np.array([[1,2,0],[2,0,1]]) # Scaling values
d1 = np.array([[2,0,1],[1,2,0]])
out = a[d0[0]]*b[d1[0]] - a[d0[1]]*b[d1[1]]
``````

As one-liner -

``````a[[1,2,0]]*b[[2,0,1]] - a[[2,0,1]]*b[[1,2,0]]
``````