NumPy cross()

The numpy.cross() function computes the cross product of two vectors or arrays of vectors. The cross product of two 3D vectors results in a third vector perpendicular to both. For 2D vectors, the function returns the scalar z-component of the cross product.

Syntax

</>
Copy
numpy.cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)

Parameters

ParameterTypeDescription
aarray_likeFirst input vector or array of vectors.
barray_likeSecond input vector or array of vectors.
axisaint, optionalSpecifies the axis in a that represents the vector(s). Default is the last axis.
axisbint, optionalSpecifies the axis in b that represents the vector(s). Default is the last axis.
axiscint, optionalSpecifies the axis in the output array where the result should be stored. Ignored for 2D vectors.
axisint, optionalIf provided, overrides axisa, axisb, and axisc. Specifies the axis along which vectors are defined.

Return Value

Returns an array representing the cross product of the input vectors. If the input vectors are 3D, the result is a 3D vector. If both vectors are 2D, the function returns a scalar value representing the z-component of the cross product.


Examples

1. Computing the Cross Product of Two 3D Vectors

This example calculates the cross product of two 3D vectors.

</>
Copy
import numpy as np

# Define two 3D vectors
vector_a = np.array([1, 2, 3])
vector_b = np.array([4, 5, 6])

# Compute the cross product
result = np.cross(vector_a, vector_b)

# Print the result
print("Cross product of vector_a and vector_b:", result)

Output:

Cross product of vector_a and vector_b: [-3  6 -3]