Elementwise Multiplication Across Batches

Suppose I have a tensor of images as follows:

A=torch.rand(10, 3, 28, 28)

And suppose I have another tensor that I want to be multiplied elementwise by all images and layers of A as follows:

B=torch.rand(28, 28)

Is there an easier/faster/more efficient way to do this, instead of the following?:

B=torch.cat([torch.cat([B.unsqueeze(0)]*A.size()[-3]).unsqueeze(0)]*A.size()[-4])
C=A*B

TIA

Hi J!

You may use the expression for element-wise multiplication, C = A * B,
and pytorch will use broadcasting to multiply all of the images and channels
in A by B.

Note that broadcasting treats “missing” leading dimensions as if they were
singleton dimensions, so C = A * B.unsqueeze (0).unsqueeze (0)
would be equivalent (but, to be clear, there is no reason, even stylistic,
to use unsqueeze() in this case).

Best.

K. Frank

I see. Not sure why I was getting an error before, but I’m not seeing it now. Thank you.