w3resource

Multiply 3D array by 1D array using NumPy Broadcasting


3. 3D Array Multiplication with 1D Array

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.

For more Practice: Solve these Related Problems:

  • Multiply each slice of a 3D array by a 1D array and then sum the products along the last axis.
  • Implement a function that scales the last dimension of a 3D array using a 1D array and returns the modified array.
  • Create a program that multiplies a 3D array with a 1D array and then computes the element-wise difference between the original and the result.
  • Test the multiplication on arrays with random float values to verify broadcasting across the last axis.

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.



Follow us on Facebook and Twitter for latest update.