Search code examples
python-3.xperformancenumpyadditionzero-padding

Fastest solution for general padded addition in numpy


I need to add 2 dim arrays of variable sizes to each other. There are many methods to do this!

Typical sizes are a few thousand by a few hundred (as this may impact scaling!). Need to carry out hundreds of thousands of these additions. The first dimension is guaranteed to be the same in my case, but subarrays are variable length.

working smaller example:

a = np.ones(shape=(20,20))
b = np.ones(shape=(20,18))
c = a+b # Expected error

b.resize(a.shape)
c = b+c # This works!

Are there faster ways of doing this? I am interested in other pythonic solutions like above, but also what might be truly fastest regardless of complexity (it is that kind of project where speed is mostly king, but not so much as to write it in C).


Solution

  • If you don't mind changing a, you could do

    a[:, :b.shape[1]] += b
    

    I suspect this will be faster than padding b and then adding, but things like this need to be tested with realistic data.