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.
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))
Sample 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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics