Open In App

How to compute the cross product of two given vectors using NumPy?

Last Updated : 25 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 library
import numpy as np
 
# declare vectors
x = [1, 2]
y = [3, 4]
 
# find cross product of
# two given vectors
result = np.cross(x, y)
 
# show the result
print(result)


Output:

-2

Example 2: Cross product of 2d-arrays.

Python3




# import library
import numpy as np
 
# declare vectors
x = [[1, 2], [3, 4]]
y = [[5, 6], [7, 8]]
 
# find cross product of
# two given vectors
result = np.cross(x, y)
 
# show the result
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 library
import numpy as np
 
# initialize X and Y matrices
X = np.array([[1,2,3],
              [2,5,6],
              [1,2,1]])
Y = np.array([[-5, 5,-10],
              [ 1, 2, 8],
              [ 5, 4, 1]])
 
# perform cross-product using @
Z = X @ Y
 
# print the resulting matrix
print(Z)


Output:

[[12 21  9]
[25 44 26]
[ 2 13  7]]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads