# Multiply pytorch 4 dimension array with scalar value

I have array A with dimension [ 1, 3, 256, 256]. I want to multiply A with vector B having value B=[1 2 3]. It means all the values of vector A channel 1[ A(1,1,256,256)] should multiply with constant value 1, channel 2[ A(1,2,256,256)] should multiply with constant value 2 and channel 3 with constant value 3.

How to transform B such that it gives desired result by direct multiplication A*B?

Hello,

This code seems to be doing what you want (let me know if it is not!)

``````    a = torch.ones(size=(1, 3, 8, 8), dtype=torch.float32) * 2.0
print(a)
b = torch.tensor(data=[1, 2, 3], dtype=torch.float32)
print(b)

b = b.unsqueeze(dim=0)
b = b.unsqueeze(dim=2)
b = b.unsqueeze(dim=3)
# b passes from a (1 x 3 x 1 x 1) tensor to a (1 x 3 x 8 x 8) tensor
b = b.expand_as(a)

# element wise multiplication
print(a * b)
``````

This works. But I think “b = b.expand_as(a)” in your code is not necessary as broadcasting will help.

Yes, you are right! It works. Same thing i wants. Thanks