How to perform outer addition with NumPy?

Learn, how can we perform outer addition with Python NumPy?
Submitted by Pranit Sharma, on March 07, 2023

Performing outer addition with NumPy

Suppose that we are given a numpy array and we need to perform outer addition/multiplication using some technique rather than using a for loop.

Many of NumPy's basic operators such as numpy.add(), numpy.subtract(), numpy.multiply(), etc. are known as universal functions (ufuncs)

In numpy, all universal functions that take two input arguments have an attribute called outer. With the help of this attribute, all the outer entities can be used whether in addition, subtraction, or multiplication.

Let us understand with the help of an example,

Python code to perform outer addition with NumPy

# Import numpy
import numpy as np

# Creating array
arr = np.array([1, 2, 3])

# Display Original array
print("Original array:\n",arr,"\n")

# Outer addition
res = np.add.outer(arr,arr)

# Display result
print("Outer addition:\n",res,"\n")

# Outer subtraction
res = np.subtract.outer(arr,arr)

# Display result
print("Outer subtraction:\n",res,"\n")

Output:

Example: How to perform outer addition with NumPy?

Python NumPy Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.