w3resource

Multiply 3D array by 1D array using NumPy Broadcasting

NumPy: Broadcasting Exercise-3 with Solution

Write a NumPy program that multiplies a 3D array of shape (2, 3, 4) by a 1D array of shape (4,) using broadcasting.

Sample Solution:

Python Code:

# Import the NumPy library
import numpy as np

# Create a 3D array a with shape (2, 3, 4)
a = np.array([[[1, 2, 3, 4],
               [5, 6, 7, 8],
               [9, 10, 11, 12]],

              [[13, 14, 15, 16],
               [17, 18, 19, 20],
               [21, 22, 23, 24]]])

# Create a 1D array b with shape (4,)
b = np.array([2, 3, 4, 5])

# Multiply the 3D array a by the 1D array b using broadcasting
result = a * b

# Print the original arrays and the result
print("3D Array a:\n", a)
print("1D Array b:\n", b)
print("Result of a * b:\n", result)

Output:

3D Array a:
 [[[ 1  2  3  4]
  [ 5  6  7  8]
  [ 9 10 11 12]]

 [[13 14 15 16]
  [17 18 19 20]
  [21 22 23 24]]]
1D Array b:
 [2 3 4 5]
Result of a * b:
 [[[  2   6  12  20]
  [ 10  18  28  40]
  [ 18  30  44  60]]

 [[ 26  42  60  80]
  [ 34  54  76 100]
  [ 42  66  92 120]]]

Explanation:

  • Import the NumPy library: This step imports the NumPy library, essential for numerical operations.
  • Create a 3D array a: We use np.array to create a 3D array a with shape (2, 3, 4) and the given elements.
  • Create a 1D array b: We use np.array to create a 1D array b with shape (4,) and elements [2, 3, 4, 5].
  • Multiply the 3D array a by the 1D array b using broadcasting: NumPy automatically adjusts the shape of b to match the last dimension of a and performs element-wise multiplication.
  • Print the original arrays and the result: This step prints the original 3D array a, the 1D array b, and the result of the multiplication.

Python-Numpy Code Editor:

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

Previous: Subtract 1D array from 2D array using NumPy Broadcasting.
Next: Add Scalar to 2D array using NumPy 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/multiply-3d-array-by-1d-array-using-numpy-broadcasting.php