How to compute the cross product of two given vectors using NumPy?
Last Updated :
25 Mar, 2023
Let’s see the program to compute the cross product of two given vectors using NumPy. For finding the cross product of two given vectors we are using numpy.cross() function of NumPy library.
Syntax: numpy.cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)[
Return: cross product of two (arrays of) vectors.
Let’s see the examples:
Example 1: Cross product of 1d-arrays.
Python3
import numpy as np
x = [ 1 , 2 ]
y = [ 3 , 4 ]
result = np.cross(x, y)
print (result)
|
Output:
-2
Example 2: Cross product of 2d-arrays.
Python3
import numpy as np
x = [[ 1 , 2 ], [ 3 , 4 ]]
y = [[ 5 , 6 ], [ 7 , 8 ]]
result = np.cross(x, y)
print (result)
|
Output:
[-4 -4]
Example 3: Cross product of 2D arrays using the @ operator. This method is available in python 3.5 and was introduced as a means to remove the confusion between element-wise operation(*) and cross-product (@) between two matrices.
Python3
import numpy as np
X = np.array([[ 1 , 2 , 3 ],
[ 2 , 5 , 6 ],
[ 1 , 2 , 1 ]])
Y = np.array([[ - 5 , 5 , - 10 ],
[ 1 , 2 , 8 ],
[ 5 , 4 , 1 ]])
Z = X @ Y
print (Z)
|
Output:
[[12 21 9]
[25 44 26]
[ 2 13 7]]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...