Numpy Program to multiply each row of 2D array by 1D array using Broadcasting
Write a NumPy program that multiplies each row of a 2D array a of shape (4, 4) by a 1D array b of shape (4,) using broadcasting.
Sample Solution:
Python Code:
import numpy as np
# Initialize the 2D array of shape (4, 4)
a = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
# Initialize the 1D array of shape (4,)
b = np.array([2, 4, 6, 8])
# Perform element-wise multiplication using broadcasting
result_array = a * b
# Display the result
print(result_array)
Output:
[[ 2 8 18 32] [ 10 24 42 64] [ 18 40 66 96] [ 26 56 90 128]]
Explanation:
- Importing numpy: We first import the numpy library for array manipulations.
- Initializing arrays: A 2D array of shape (4, 4) and a 1D array of shape (4,) are initialized.
- Broadcasting and Multiplication: Element-wise multiplication is performed between each row of the 2D array and the 1D array using broadcasting.
- Displaying result: The resulting array is printed out.
Python-Numpy Code Editor:
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