w3resource

NumPy: Compute the inner product of two given vectors

NumPy: Basic Exercise-33 with Solution

Write a NumPy program to compute the inner product of two given vectors.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating NumPy arrays 'x' and 'y' with respective values [4, 5] and [7, 10]
x = np.array([4, 5])
y = np.array([7, 10])

# Printing a message indicating the original vectors 'x' and 'y'
print("Original vectors:")
print(x)
print(y)

# Calculating and printing the inner product of the vectors 'x' and 'y' using np.dot()
print("Inner product of said vectors:")
print(np.dot(x, y))

Sample Output:

Original vectors:
[4 5]
[ 7 10]
Inner product of said vectors:
78                         

Explanation:

The above code creates two 1D arrays 'x' and 'y' and calculates their dot product, which is then printed as the output.

x = np.array([4, 5]): This statement creates a 1D array 'x' with the elements [4, 5].

y = np.array([7, 10]): This statement creates a 1D array 'y' with the elements [7, 10].

Finally in ‘print(np.dot(x, y))’ statement np.dot() function is used to calculate the dot product of the two 1D arrays 'x' and 'y'. The dot product is computed as (4 * 7) + (5 * 10) = 28 + 50 = 78. The result, 78, is then printed to the console.

Pictorial Presentation:

NumPy: Compute the inner product of two given vectors.

Python-Numpy Code Editor:

Previous: NumPy program to compute sum of all elements, sum of each column and sum of each row of an given array.
Next: NumPy program to add a vector to each row of a given matrix.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.