w3resource

NumPy: Multiply two given arrays of same size element-by-element

NumPy: Basic Exercise-59 with Solution

Write a NumPy program to multiply two given arrays of the same size element-by-element.

This problem involves writing a NumPy program to perform element-wise multiplication of two given arrays of the same size. The task requires utilizing NumPy's array manipulation capabilities, specifically the "numpy.multiply" function, to efficiently multiply corresponding elements of the arrays. By applying element-wise multiplication, the program generates a new array containing the products of the corresponding elements from the two input arrays, facilitating various computational tasks such as linear algebra operations or data transformations.

Sample Solution:

Python Code:

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

# Creating two NumPy arrays 'nums1' and 'nums2' containing 2x3 matrices
nums1 = np.array([[2, 5, 2],
              [1, 5, 5]])

nums2 = np.array([[5, 3, 4],
              [3, 2, 5]])

# Printing the contents of 'nums1' array
print("Array1:") 
print(nums1)

# Printing the contents of 'nums2' array
print("Array2:") 
print(nums2)

# Performing element-wise multiplication of arrays 'nums1' and 'nums2' using np.multiply()
# This operation multiplies corresponding elements of the two arrays
print("\nMultiply said arrays of same size element-by-element:")
print(np.multiply(nums1, nums2)) 

Output:

Array1:
[[2 5 2]
 [1 5 5]]
Array2:
[[5 3 4]
 [3 2 5]]

Multiply said arrays of same size element-by-element:
[[10 15  8]
 [ 3 10 25]]

Explanation:

In the above code -

nums1 = np.array([[2, 5, 2], [1, 5, 5]]): Creates a 2D NumPy array of shape (2, 3) with the specified values and stores in a variable ‘nums1’

nums2 = np.array([[5, 3, 4], [3, 2, 5]]): Creates another 2D NumPy array of shape (2, 3) with the specified values and stores in a variable ‘nums2’

print(np.multiply(nums1, nums2)): Uses the np.multiply() function to perform element-wise multiplication of the two arrays nums1 and nums2. The resulting array has the same shape as the input arrays (2, 3).

Python-Numpy Code Editor:

Previous: NumPy program to swap rows and columns of a given array in reverse order.
Next: NumPy: Array Object Exercises Home

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://198.211.115.131/python-exercises/numpy/basic/numpy-basic-exercise-59.php