This seems like it should be a simple operation, but for the life of me I can't figure it out. I have two arrays of incompatible shape that can't be broadcast together.
A1.shape == (2, 10, 10)
A2.shape == (2, 300)
I would like to add the two arrays along the first dimension, so that the result is an array with shape:
Result.shape == (2, 10, 10, 300)
In other words:
Result[0, 2, 3, 122] == A1[0, 2, 3] A2[0, 122]
Result[1, 2, 3, 122] == A1[1, 2, 3] A2[1, 122]
Can I do this vectorised, without resorting to looping?
CodePudding user response:
To make numpy do the broadcasting, you should insert new axes to broadcast over. (this is pointed out by Heisenbugs in the comments)
Result = A1[:,:,:,np.newaxis] A2[:,np.newaxis,np.newaxis,:]
Do note that np.newaxis is None
, so you can write None
if you like. But I think np.newaxis
is more readable.