Multiplying tensors along selected dimensions

I want to scale the matrices by a group of scalar values, consider input to be input tensor of dim [a,b,c,d](a being batch size and b being number of matrices) and scaling factors of dim [e] (Indicating e scaling factors). Is there any elegant way to do this other than looping on each factor and concat the final output

input = torch.rand((1500, 4, 3, 3))
scalar = torch.rand((12))
out = comb * scalar[None, :, None, None]

What would be the desired ouput shape?
If you want to create an output of [1500, 12, 4, 3, 3], you could use this code:

input = torch.rand((1500, 4, 3, 3))
scalar = torch.rand((12))
out = input.unsqueeze(1) * scalar[None, :, None, None, None]
print(out.shape)
> torch.Size([1500, 12, 4, 3, 3])

for i in range(scalar.size(0)):
    print((out[:, i] == input * scalar[i]).all())
> tensor(True)
tensor(True)
...

Thanks for your time @ptrblck!!
The desired shape would be [1500, 48, 3, 3] .

In that case you could flatten dim1 and dim2 to a single dimension via:

out = out.view(out.size(0), -1, out.size(3), out.size(4))
1 Like

Yes that’ll work perfectly!!
Thank you so much!