w3resource

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

NumPy: Broadcasting Exercise-15 with Solution

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:

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

Previous: Numpy Program to add 1D array to each 2D slice of 3D array using Broadcasting.
Next: Numpy Program to subtract 1D array from 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://w3resource.com/python-exercises/numpy/numpy-program-to-add-arrays-of-shapes-2-1-3-and-1-4-1-using-broadcasting.php