w3resource

Python Program to multiply 2D array and Scalar using Broadcasting

NumPy: Broadcasting Exercise-12 with Solution

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:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Numpy Program to add 3D array and 2D array using Broadcasting.
Next: Numpy Program to multiply each row of 2D array by 1D array using Broadcasting.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/python-program-to-multiply-2d-array-and-scalar-using-broadcasting.php