w3resource

Python Program to multiply 2D array and Scalar using Broadcasting


Write a NymPy program that creates a 2D array x of shape (4, 4) and a scalar y. Perform element-wise multiplication of a and b using broadcasting.

Sample Solution:

Python Code:

import numpy as np

# Initialize the 2D array of shape (4, 4)
x = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])

# Initialize the scalar
y = 3

# Perform element-wise multiplication using broadcasting
result_array = x * y

# Display the result
print(result_array)

Output:

[[ 3  6  9 12]
 [15 18 21 24]
 [27 30 33 36]
 [39 42 45 48]]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Initializing the 2D array: A 2D array of shape (4, 4) is initialized.
  • Initializing the scalar: A scalar value is initialized.
  • Broadcasting and Multiplication: Element-wise multiplication is performed between the 2D array and the scalar using broadcasting.
  • Displaying result: The resulting array is printed out.

Python-Numpy Code Editor: