Element-wise multiply Nd matrix with 1D gate along specific dimension


I’m trying to elementwise-multiply a 4D matrix M of size [100,8,1,400] with a tensor gates of size [8] along a specific dimension.
I can’t get it to work by reshaping, bmm, or elementwise products. What I want is this, but then vectorized:

for i,gate in enumerate(gates):
    M[:,i,:,:] *= gate

It doesn’t seem like this should be hard, but I can’t seem to figure it out. Any help is appreciated!

I got it to work. It’s not pretty, but gets the job done without a for loop:

gate = gate.view(8,1,1,1).expand_as(M.transpose(1,0))
M = (gate*M.transpose(1,0)).transpose(1,0)