Say I have two numpy arrays, for example
import numpy as np
A = np.arange(5*3*3*2).reshape(5, 3, 3, 2)
B = np.arange(3*3).reshape(3, 3)
If I want to add A and B across a shared axis, I would just do
C = A + B[None, :, :, None]
# C has shape (5, 3, 3, 2) which is what I want
I want to write a write function that generalizes this kind of summation but am not how to get started. It would look something like
def mask(M, Mshape, out_shape):
# not sure what to put here
pass
def add_tensors(A, B, Ashape, Bshape, out_shape):
# Here I mask A, B so that it has shape out_shape
A = mask(A, Aaxis, out_shape)
B = mask(B, Baxis, out_shape)
return A + B
Any suggestions? Is it possible to make this a ufunc?