Numpy Adding two vectors with different sizes

Question:

If I have two numpy arrays of different sizes, how can I superimpose them.

a = numpy([0, 10, 20, 30])
b = numpy([20, 30, 40, 50, 60, 70])

What is the cleanest way to add these two vectors to produce a new vector (20, 40, 60, 80, 60, 70)?

This is my generic question. For background, I am specifically applying a Green’s transform function and need to superimpose the results for each time step in the evaulation unto the responses previously accumulated.

Asked By: tnt

||

Answers:

This could be what you are looking for

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

basically you copy the longer one and then add in-place the shorter one

Answered By: 6502

If you know that b is higher dimension, then:

>>> a.resize(b.shape)
>>> c = a+b

is all you need.

Answered By: Eric Wilson

Very similar to the one above, but a little more compact:

l = sorted((a, b), key=len)
c = l[1].copy()
c[:len(l[0])] += l[0]
Answered By: Tobia Marcucci
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.