w3resource

NumPy: Compute the inner product of two given vectors

NumPy: Basic Exercise-33 with Solution

Compute Inner Product of Vectors

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

This problem involves writing a NumPy program to compute the inner product of two given vectors. The inner product, also known as the dot product, involves multiplying the corresponding elements of the vectors and summing the results. By utilizing NumPy's array manipulation capabilities, particularly the dot function, the program efficiently calculates the inner product, providing a scalar value representing the measure of similarity or projection of one vector onto another.

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))

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.

Visual 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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/numpy/basic/numpy-basic-exercise-33.php