w3resource

NumPy: Generate inner, outer, and cross products of matrices and vectors


Write a NumPy program to generate inner, outer, and cross products of matrices and vectors.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating NumPy arrays 'x' and 'y'
x = np.array([1, 4, 0], float)
y = np.array([2, 2, 1], float)

# Displaying matrices and vectors 'x' and 'y'
print("Matrices and vectors.")
print("x:")
print(x)
print("y:")
print(y)

# Computing the inner product of vectors 'x' and 'y'
print("Inner product of x and y:")
print(np.inner(x, y))

# Computing the outer product of vectors 'x' and 'y'
print("Outer product of x and y:")
print(np.outer(x, y))

# Computing the cross product of vectors 'x' and 'y'
print("Cross product of x and y:")
print(np.cross(x, y))

Sample Output:

Matrices and vectors.                                                  
x:                                                                     
[ 1.  4.  0.]                                                          
y:                                                                     
[ 2.  2.  1.]                                                          
Inner product of x and y:                                              
10.0                                                                   
Outer product of x and y:                                              
[[ 2.  2.  1.]                                                         
 [ 8.  8.  4.]                                                         
 [ 0.  0.  0.]]                                                        
Cross product of x and y:                                              
[ 4. -1. -6.]

Explanation:

np.inner(x, y) computes the inner product of two arrays. For 1-D arrays, it is the sum of the product of the corresponding elements. For higher dimensions, it is a sum product over the last axes.In the given code, x and y are 1-D arrays, and the output is the sum of the element-wise product of x and y, which is 10.

np.outer(x, y) computes the outer product of two arrays. For 1-D arrays, it returns the matrix of all possible products of the elements of x and the elements of y.In the given code, x and y are 1-D arrays, and the output is a 2-D array where each element is the product of the corresponding elements of x and y.

np.cross(x, y) computes the cross product of two arrays in a 3-dimensional space. The cross product of two 1-D arrays returns a vector perpendicular to both input vectors. In the given code, x and y are 1-D arrays, and the output is the cross product of x and y, which is a 1-D array [ 4., -1., -6.]. Since the input vectors are in a 3-dimensional space, the cross product is computed using the right-hand rule.

Python-Numpy Code Editor: