Element-wise Multiplication of 2D arrays using np.multiply in NumPy
NumPy: Universal Functions Exercise-4 with Solution
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.
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.
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/element-wise-multiplication-of-2d-arrays-using-np-dot-multiply-in-numpy.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics