Adding Two Vectors with Different Sizes in Python

Including Cython, Jython, IronPython, PyPy, Django framework, and interpreters: Ipython, IPython Jupyter/Notebook, CPython


Post Reply
User avatar
Eli
Senior Expert Member
Reactions: 185
Posts: 5450
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#1

Sometimes a need arises to add two Numpy arrays, which are simply vectors in mathematical terms, of different sizes. Suppose you have two Numpy arrays, x and y with differing lengths, then the logical and convenient way to add them is by the simple python code below.

  1. import numpy as np
  2.  
  3. x = np.array([0, 1, 5, 10, 20, 30, 40, 50])
  4. y = np.array([1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
  5.  
  6. if len(x) < len(y):
  7.     z = y.copy()
  8.     z[:len(x)] += x
  9. else:
  10.     z = x.copy()
  11.     z[:len(y)] += y
  12.  
  13. print(z)

0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
Post Reply
  • Similar Topics
    Replies
    Views
    Last post

Return to “Python Programming”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 0 guests