NumPy: Generate inner, outer, and cross products of matrices and vectors
14. Inner, Outer, and Cross Products
Write a NumPy program to generate inner, outer, and cross products of matrices and vectors.
Sample Solution:
Python Code:
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.
For more Practice: Solve these Related Problems:
- Implement a function that computes the inner, outer, and cross products for two given vectors and returns all three.
- Test the functions on 1D arrays and verify that the inner and outer products yield expected dimensions.
- Compare the cross product output with manual computations on two 3D vectors.
- Apply the outer product function on arrays with varying lengths to observe the resulting 2D matrix shape.
Go to:
PREV : Inner Product of Arrays
NEXT : Matrix Product of Two Arrays
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.