w3resource

Numpy Program to reshape and add 1D arrays using Broadcasting

NumPy: Broadcasting Exercise-9 with Solution

Write a NumPy program that creates two 1D arrays x of shape (5,) and y of shape (5,). Reshape them to (5, 1) and (1, 5) respectively, and perform element-wise addition using broadcasting.

Sample Solution:

Python Code:

import numpy as np

# Initialize two 1D arrays of shape (5,)
x = np.array([1, 2, 3, 4, 5])
y = np.array([10, 20, 30, 40, 50])

# Reshape the arrays to (5, 1) and (1, 5) respectively
x_reshaped = x.reshape((5, 1))
y_reshaped = y.reshape((1, 5))

# Perform element-wise addition using broadcasting
result_array = x_reshaped + y_reshaped

# Display the result
print(result_array)

Output:

[[11 21 31 41 51]
 [12 22 32 42 52]
 [13 23 33 43 53]
 [14 24 34 44 54]
 [15 25 35 45 55]]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Initializing arrays: Two 1D arrays of shape (5,) are initialized.
  • Reshaping arrays: The arrays are reshaped to (5, 1) and (1, 5) respectively to enable broadcasting.
  • Broadcasting and Addition: Element-wise addition is performed using broadcasting between the reshaped arrays.
  • 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 subtract 1D array from 2D slices of 3D array.
Next: Numpy Program to divide 2D array by 1D 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://198.211.115.131/python-exercises/numpy/numpy-program-to-reshape-and-add-1d-arrays-using-broadcasting.php