Vector Addition in Numpy

  1. Use the numpy.add() Function to Perform Vector Addition in Numpy
  2. Use the numpy.ndarray.__add__() Function to Perform Vector Addition in Numpy
  3. Use the + Operator to Perform Vector Addition in Numpy
  4. What to Do When the Two Arrays Are Not of Equal Size

A single-dimensional array of lists can be considered a vector. In Python, we use the numpy module to perform different operations on arrays.

In this tutorial, we will discuss how to perform vector addition in Python.

When we say vector addition, what it means is that we will add two arrays. The arrays need to be of the same length in all the methods discussed below; otherwise, a ValueError is raised.

Use the numpy.add() Function to Perform Vector Addition in Numpy

The add() function from the numpy module can be used to add two arrays. It performs addition over arrays that have the same size with elements at every corresponding position getting summed up.

For example,

import numpy as np
 
arr1 = np.array([3, 2, 1])
arr2 = np.array([1, 2, 3])
   
s = np.add(arr1, arr2)  
print(s)  

Output:

[4 4 4]

Use the numpy.ndarray.__add__() Function to Perform Vector Addition in Numpy

The numpy.ndarray.__add__() function is used to add some value to every element of the array. We can use it to perform vector addition by passing the second array to this function.

For example,

import numpy as np
 
arr1 = np.array([3, 2, 1])
arr2 = np.array([1, 2, 3])
   
s = arr1.__add__(arr2)  
print(s)  

Output:

[4 4 4]

Use the + Operator to Perform Vector Addition in Numpy

We can eliminate the use of any function by simply using the arithmetic + operator to calculate the sum of two arrays.

For example,

import numpy as np
 
arr1 = np.array([3, 2, 1])
arr2 = np.array([1, 2, 3])
   
s = arr1 + arr2  
print(s)  

Output:

[4 4 4]

What to Do When the Two Arrays Are Not of Equal Size

It has been discussed earlier that all the above methods will return ValueError if the arrays are not of the same size. For such situations, we can either fill the smaller array with 0s manually or use the numpy.pad() function to perform addition normally or create our own function to perform addition.

See the code below.

import numpy as np
a = np.array([3, 2, 1])
b = np.array([1, 2])

def unequal_add(a,b):
    if len(a) < len(b):
        c = b.copy()
        c[:len(a)] += a
    else:
        c = a.copy()
        c[:len(b)] += b
    return(c)


print(unequal_add(a,b))

Output:

[4 4 1]

What we do is copy the longer array and add the elements of the smaller array to the longer array. This method will consume a lot of memory.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.