Numpy Program to add arrays of Shapes (2, 1, 3) and (1, 4, 1) using Broadcasting
15. Broadcast Addition for 3D and 1D Arrays
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.
For more Practice: Solve these Related Problems:
- Given arrays of shapes (2, 1, 3) and (1, 4, 1), write a function that performs element-wise addition to produce a (2, 4, 3) array.
- Implement a solution that uses np.broadcast_to to manually broadcast arrays to the desired shape before adding.
- Create a program that checks the shapes of the input arrays and automatically reshapes them to be broadcast-compatible.
- Test the addition on sample arrays with known values to verify the correctness of the resulting 3D array.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics