w3resource

Numpy Program to multiply each row of 2D array by 1D array using Broadcasting

NumPy: Broadcasting Exercise-13 with Solution

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:

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

Previous: Python Program to multiply 2D array and Scalar using Broadcasting.
Next: Numpy Program to add 1D array to each 2D slice of 3D 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/numpy-program-to-multiply-each-row-of-2d-array-by-1d-array.php