w3resource

Numpy Program to add arrays of Shapes (2, 1, 3) and (1, 4, 1) using Broadcasting


Given two arrays, x of shape (2, 1, 3) and y of shape (1, 4, 1), use broadcasting write a NumPy program to obtain a result of shape (2, 4, 3) through element-wise addition.

Sample Solution:

Python Code:

import numpy as np

# Initialize the array x of shape (2, 1, 3)
x = np.array([[[1, 2, 3]], 
              [[4, 5, 6]]])

# Initialize the array y of shape (1, 4, 1)
y = np.array([[[ 7], [ 8], [ 9], [10]]])

# Perform element-wise addition using broadcasting
result_array = x + y

# Display the result
print(result_array)

Output:

[[[ 8  9 10]
  [ 9 10 11]
  [10 11 12]
  [11 12 13]]

 [[11 12 13]
  [12 13 14]
  [13 14 15]
  [14 15 16]]]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Initializing arrays: Arrays x of shape (2, 1, 3) and y of shape (1, 4, 1) are initialized.
  • Broadcasting and Addition: Element-wise addition is performed using broadcasting, resulting in an array of shape (2, 4, 3).
  • Displaying result: The resulting array is printed out.

Python-Numpy Code Editor: