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: