What is the numpy.cross() function?
Overview
The numpy.cross() function in NumPy is used to compute the cross product of two given vector arrays.
Syntax
numpy.cross(a, b, axisa =- 1, axisb =- 1, axisc =- 1, axis = None)
Parameter value
The numpy.cross() function takes the following parameter values:
-
a(required): This is an array_like component of the first vector. -
b(required): This is an array_like component of the second vector. -
axisa(optional): This is the axis of the first vector that defines it. Its default value is the last axis. -
axisb(optional): This is the axis of the second vector that defines it. Its default value is the last axis. -
axisc(optional): This is the axis of the third vector that contains the cross product vector. -
axis(optional): If defined, it represents the axis of the first, second, and third vectors and cross products. In essence, it overrides theaxisa,axisbandaxisc.
Return value
The numpy.cross() function returns a vector cross product.
Note: It’s worth mentioning that a
ValueErroris raised if the dimensions ofaand/orbare not equal to or .
Code
import numpy as np# creating vectors a and b with dimensions 3a = [4, 3, 8]b = [1, 9, 3]# creating multiple vectors x and y with dimensions 3x = np.array([[6, 3, 7], [3, 9, 1], [8, 8, 0]])y = np.array([[8, 8, 0], [1, 9, 3], [6, 3, 7]])# computing the cross product with axis' definedmyarray1 = np.cross(a, b, axisa = 0, axisb = 0)myarray2 = np.cross(x, y, axisa = 0, axisb = 0)# computing the cross product without defining axismyarray3 = np.cross(x, y)# printing vector cross productsprint("Cross product of vectors 'a' and 'b':\n", myarray1)print("\nCross product of vectors 'x' and 'y' with 'axisa' and 'axisb' defined:\n", myarray2)print("\nCross product of vectors 'x' and 'y' without defining axis:\n", myarray3)
Explanation
-
Line 1: We import the
numpymodule. -
Lines 4-5: We create the vector components
aandbof dimensions 3. -
Line 8-9: We create multiple vectors
xandywith dimensions 3. -
Line 12: We compute cross products of vectors
a,bwithaxisaandaxisbequal to 0. -
Line 13: We compute cross products of vectors
x,ywithaxisaandaxisbequal to 0. -
Line 16: We compute cross products of vectors
x,ywithout any axis. -
Line 19-21: We print the cross product of vectors stored in variable2
myarray1,myarray2, andmyarray3.