w3resource

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

NumPy Mathematics: Exercise-14 with Solution

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

Sample Solution:-

Python Code:

import numpy as np
x = np.array([1, 4, 0], float)
y = np.array([2, 2, 1], float)
print("Matrices and vectors.")
print("x:")
print(x)
print("y:")
print(y)
print("Inner product of x and y:")
print(np.inner(x, y))
print("Outer product of x and y:")
print(np.outer(x, 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.]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to create an inner product of two arrays.
Next: Write a NumPy program to generate a matrix product of two arrays.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Getting rid of unwanted characters:

You can get rid of whitespaces or any specific character using strip methods in Python. You can use either plain strip for both sides, lstrip for the left side and rstrip for the right side only.

str="+++Welcome python+++"
str.strip()

print(str)

Output:

+++Welcome python+++