Python Program to multiply 2D array and Scalar using Broadcasting
12. Scalar Multiplication on a 2D Array
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.
For more Practice: Solve these Related Problems:
- Multiply a 2D array by a scalar value using broadcasting and then compute the sum of the resulting array.
- Create a function that scales a 2D array by a given scalar and verifies that the array’s shape remains unchanged.
- Implement a solution that multiplies a 2D array by a scalar and then adds a constant to each element for further transformation.
- Test the scalar multiplication on arrays with various dtypes to ensure consistent type promotion.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics