Home »
Python »
Python Programs
NumPy: Adding two vectors with different sizes
Given two vectors with different sizes, we have to add them using Python NumPy.
By Pranit Sharma Last updated : December 26, 2023
Problem statement
Given two vectors with different sizes, we have to add them using Python NumPy.
For example, if we have two vectors A and B as [0, 10, 20, 30] and [20, 30, 40, 50, 60, 70] and we need to add these vectors of different lengths.
Add two vectors with different sizes
To add two vectors with different sizes, we need to play with the length of both vectors and make some copies of the vectors. We need to check if the length of A is less than B then we need to make a copy of B and then add the elements of A to it.
Also, if the length of B is less than A, we need to make a copy of A and add the elements of B to it.
Let us understand with the help of an example,
Python code to add two vectors with different sizes
# Import numpy
import numpy as np
# Creating vectors
v1 = np.array([0, 10, 20, 30])
v2 = np.array([20, 30, 40, 50, 60, 70])
# Display Original vectors
print("Original vector 1:\n",v1,"\n")
print("Original vector 2:\n",v2,"\n")
# Adding both vectors
if len(v1) < len(v2):
res = v2.copy()
res[:len(v1)] += v1
else:
res = v1.copy()
res[:len(v2)] += v2
# Display result
print("Result:\n",res)
Output
In this example, we have used the following Python basic topics that you should learn:
Python NumPy Programs »
Advertisement
Advertisement