Element-wise Multiplication of 2D arrays using np.multiply in NumPy
4. Ufunc: Element-wise Multiplication of 2D Arrays
Element-wise Multiplication:
Write a NumPy program that uses the np.multiply ufunc to perform element-wise multiplication of two 2D arrays of the same shape.
Sample Solution:
Python Code:
import numpy as np
# Create two 2D NumPy arrays of the same shape (3, 3) with random integers
array_2d_1 = np.random.randint(0, 10, size=(3, 3))
array_2d_2 = np.random.randint(0, 10, size=(3, 3))
# Use the np.multiply ufunc to perform element-wise multiplication
result_array = np.multiply(array_2d_1, array_2d_2)
# Print the original arrays and the resulting array
print('Original 2D array 1:\n', array_2d_1)
print('Original 2D array 2:\n', array_2d_2)
print('Resulting array after element-wise multiplication:\n', result_array)
Output:
Original 2D array 1: [[6 4 1] [0 0 2] [9 0 1]] Original 2D array 2: [[2 2 1] [6 3 6] [4 2 8]] Resulting array after element-wise multiplication: [[12 8 1] [ 0 0 12] [36 0 8]]
Explanation:
- Import Libraries:
- Imported numpy as "np" for array creation and manipulation.
- Create Two 2D NumPy Arrays:
- Created two 2D NumPy arrays named array_2d_1 and array_2d_2 with random integers ranging from 0 to 9 and a shape of (3, 3).
- Element-wise multiplication with np.multiply:
- Used the np.multiply "ufunc" to perform element-wise multiplication of two 2D arrays.
- Print Results:
- Print the two original 2D arrays and the resulting array after element-wise multiplication.
For more Practice: Solve these Related Problems:
- Write a Numpy program to multiply two 2D arrays element-wise using np.multiply and then apply a threshold to the result.
- Write a Numpy program to perform element-wise multiplication of two 2D arrays and then normalize the resulting array.
- Write a Numpy program to compare np.multiply with manual element-wise multiplication on 2D arrays with random integer values.
- Write a Numpy program to use np.multiply on two 2D arrays and then compute the sum of each row from the product array.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.Previous: Add 1D array to each Row of 2D array using np.add in NumPy.
Next: Apply np.sin, np.cos, and np.tan ufuncs to angles in NumPy.
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