w3resource

NumPy: Multiply the values ​​of two given vectors

NumPy: Basic Exercise-24 with Solution

Multiply Two Vectors

Write a NumPy program to multiply the values ​​of two given vectors.

This problem entails writing a NumPy program to perform element-wise multiplication of two given vectors. The task involves leveraging NumPy's array manipulation capabilities to multiply the corresponding elements from each vector efficiently, resulting in a new vector containing the products of their values.

Sample Solution :

Python Code :

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

# Creating a NumPy array 'x' containing elements 1, 8, 3, and 5
x = np.array([1, 8, 3, 5])

# Printing a message indicating Vector-1 and displaying the array 'x'
print("Vector-1")
print(x)

# Generating a NumPy array 'y' containing 4 random integers between 0 and 10 using np.random.randint()
y = np.random.randint(0, 11, 4)

# Printing a message indicating Vector-2 and displaying the array 'y'
print("Vector-2")
print(y)

# Performing element-wise multiplication between arrays 'x' and 'y' and storing the result in the 'result' variable
result = x * y

# Printing a message indicating the multiplication of the values of the two said vectors and displaying the result
print("Multiply the values of two said vectors:")
print(result) 

Output:

Vector-1
[1 8 3 5]
Vector-2
[1 6 4 6]
Multiply the values of two said vectors:
[ 1 48 12 30]                         

Explanation:

In the above code -

np.array([1, 8, 3, 5]) creates a NumPy array 'x' with the specified elements [1, 8, 3, 5].

np.random.randint(0, 11, 4) creates a NumPy array 'y' of 4 random integers between 0 (inclusive) and 11 (exclusive).

x * y performs element-wise multiplication between the arrays 'x' and 'y'. The corresponding elements of 'x' and 'y' are multiplied together, resulting in a new array 'result' with the same shape as the input arrays.

Python-Numpy Code Editor:

Previous: NumPy program to create a vector of length 5 filled with arbitrary integers from 0 to 10.
Next: NumPy program to create a 3x4 matrix filled with values ​​from 10 to 21.

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-24.php