numpy numpy.cross More Flexibility with Multiple Cross Products


Example

In our last two examples, numpy assumed that a[0,:] was the first vector, a[1,:] the second, and a[2,:] the third. Numpy.cross has an optional argument axisa that allows us to specify which axis defines the vectors. So,

>>> a=np.array([[1,1,1],[0,1,0],[1,0,-1]])
>>> b=np.array([0,0,1])
>>> np.cross(a,b)
array([[ 1, -1,  0],
       [ 1,  0,  0],
       [ 0, -1,  0]])
>>> np.cross(a,b,axisa=0)
array([[ 0, -1,  0],
       [ 1, -1,  0],
       [ 0, -1,  0]])
>>> np.cross(a,b,axisa=1)
array([[ 1, -1,  0],
       [ 1,  0,  0],
       [ 0, -1,  0]])

The axisa=1 result and the default result are both (np.cross([1,1,1],b), np.cross([0,1,0],b), np.cross([1,0,-1],b)). By default, axisa always indicates the last (most slowly varying) axis of the array. The axisa=0 result is (np.cross([1,0,1],b), np.cross([1,1,0],b), np.cross([1,0,-1],b)).

A similar optional parameter, axisb, performs the same function for the b input, if it is also a 2-dimensional array.

Parameters axisa and axisb tell numpy how to distribute the input data. A third parameter, axisc tells numpy how to distribute the output if a or b is multi-dimensional. Using the same inputs a and b as above, we get

>>> np.cross(a,b,1)
array([[ 1, -1,  0],
       [ 1,  0,  0],
       [ 0, -1,  0]])
>>> np.cross(a,b,1,axisc=0)
array([[ 1,  1,  0],
       [-1,  0, -1],
       [ 0,  0,  0]])
>>> np.cross(a,b,1,axisc=1)
array([[ 1, -1,  0],
       [ 1,  0,  0],
       [ 0, -1,  0]])

So axisc=1 and the default axisc both give the same result, that is, the elements of each vector are contiguous in the fastest moving index of the output array. axisc is by default the last axis of the array. axisc=0 distributes the elements of each vector across the slowest varying dimension of the array.

If you want axisa, axisb, and axisc to all have the same value, you do not need to set all three parameters. You can set a fourth parameter, axis, to the needed single value and the other three parameters will be automatically set. axis overrides axisa, axisb, or axisc if any of them are present in the function call.