![]() |
VOOZH | about |
Working with vector and matrix operations is a fundamental part of scientific computing and data analysis. NumPy is a Python library that computes various types of vector and matrix products. Let's discuss how to find the inner, outer and cross products of matrices and vectors using NumPy in Python.
The inner product (or dot product) is obtained by multiplying corresponding elements of two arrays and summing them. For matrices, NumPy computes it row-wise.
numpy.inner(arr1, arr2)
Example: Below we compute the inner product of two vectors and two matrices using np.inner().
Inner product of vectors a and b = 66 Inner product of matrices x and y = [[17 52] [13 62]]
Explanation:
The outer product of two vectors creates a matrix where each element is the product of elements from both vectors. For matrices, they are flattened to 1D before applying the operation.
numpy.outer(arr1, arr2, out = None)
Example: Here we calculate the outer product of vectors and matrices using np.outer().
Output
Outer product of vectors a and b =
[[ 6 20]
[18 60]]Outer product of matrices x and y =
[[ 3 45 21 9 30 24]
[ 6 90 42 18 60 48]
[ 4 60 28 12 40 32]
[ 9 135 63 27 90 72]
[ 4 60 28 12 40 32]
[ 6 90 42 18 60 48]]
Explanation:
The cross product is defined for 3D vectors and produces a new vector that is perpendicular to both input vectors. For 2D vectors, NumPy previously returned a scalar, but in NumPy ≥ 2.0 this behavior is deprecated. To avoid warnings and stay consistent, we explicitly represent 2D vectors as 3D by adding a zero in the z-axis (e.g., [x, y, 0]).
For matrices, the cross product is applied row by row, treating each row as a 3D vector.
numpy.cross(arr1 , arr2)
Example: Here we compute the cross product for vectors (converted to 3D) and for matrices row-wise.
Cross product of vectors a and b = [ 0 0 -24] Cross product of matrices x and y = [[ -9 51 -32] [-15 3 3]]
Explanation: