w3resource

Element-wise Multiplication of 2D arrays using np.multiply in NumPy


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: