w3resource

Perform element-wise addition with NumPy Broadcasting


1. Element-wise Addition with Broadcasting

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.

For more Practice: Solve these Related Problems:

  • Implement a function that adds two arrays of different shapes using broadcasting and verifies the result with manual computation.
  • Create a program that adds a scalar to an array and then adds two arrays with one of them reshaped for compatibility.
  • Write a solution that adds two arrays element-wise, then computes the cumulative sum of the result.
  • Compare the output of element-wise addition using broadcasting with the result from a loop-based implementation.

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.



Follow us on Facebook and Twitter for latest update.