In-Place addition using np.add with the Out parameter in NumPy
NumPy: Universal Functions Exercise-16 with Solution
In-place ufunc Operations:
Write a NumPy program that uses np.add with the out parameter to perform in-place addition on a NumPy array.
Sample Solution:
Python Code:
import numpy as np
# Create a NumPy array
array_x = np.array([1, 2, 3, 4, 5])
# Create another array to add
array_y = np.array([10, 20, 30, 40, 50])
# Perform in-place addition using np.add with the out parameter
np.add(array_x, array_y, out=array_x)
# Print the resulting array
print("Resulting Array after In-Place Addition:")
print(array_x)
Output:
Resulting Array after In-Place Addition: [11 22 33 44 55]
Explanation:
- Import NumPy Library:
- Import the NumPy library to handle array operations.
- Create NumPy Arrays:
- Define two NumPy arrays 'array_x' and 'array_y' with example data.
- Perform In-Place Addition:
- Use np.add() with the out parameter to add 'array_y' to 'array_x' in-place, storing the result directly in 'array_x'.
- Finally print the resulting array to verify the in-place addition.
Python-Numpy Code Editor:
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