w3resource

Perform element-wise addition with NumPy Broadcasting

NumPy: Broadcasting Exercise-1 with Solution

Given two arrays, x = np.array([1, 2, 3]) and y = np.array([[10], [20], [30]]).

Write a NumPy program that performs element-wise addition using broadcasting.

Sample Solution:

Python Code:

import numpy as np

# Create a 1D array x
x = np.array([1, 2, 3])

# Create a 2D array y
y = np.array([[10], [20], [30]])

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

print(result)

Output:

[[11 12 13]
 [21 22 23]
 [31 32 33]]

Explanation:

  • Import the NumPy library.
  • Create a 1D array x with elements [1, 2, 3].
  • Create a 2D array y with elements [[10], [20], [30]].
  • Perform element-wise addition using broadcasting, which automatically adjusts the shape of x to match y.
  • Print the result of the addition.

Python-Numpy Code Editor:

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

Previous: NumPy Broadcasting Exercises Home.
Next: Subtract 1D array from 2D array using NumPy 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/perform-element-wise-addition-with-numpy-broadcasting.php