w3resource

NumPy: Multiply the values ​​of two given vectors


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.


For more Practice: Solve these Related Problems:

  • Compute the element-wise multiplication of two vectors and then sum the result.
  • Multiply two vectors and verify the commutativity by swapping the operands.
  • Perform vector multiplication and compare the outcome with the dot product result.
  • Create two random vectors, multiply them using broadcasting, and check the resulting shape.

Go to:


PREV : Vector of Random Integers [0,10]
NEXT : Create 3x4 Matrix (10 to 21)

Python-Numpy Code Editor:

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

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.