How can I multiply a vector by a matrix in Pytorch?

Hi, I want to multiply a vector by a matrix (batch, c, h,w).
I can do it using a for loop like this :

In [68]: x=torch.rand(2,3,2,2)
In [69]: y=torch.rand(3)
In [70]: for i in range(x.shape[1]):
    ...:     x[:,i,:,:] = x[:,i,:,:]*y[i]

I know I can simply do :

In [101]: for i in range(x.shape[1]):
     ...:     var=y[i]
     ...:     x = x* var

but I want to remove the loop and make it a full vectorized multiplication.
I cant use mm, or other matrix to vector methods because it complains about the dimensions having mismatch. so Iā€™m clueless about how I can make it vectorized.

by the way, is using mul_() (as in x[:,i,:,:].mul_(y[i]) in this case has any significance against the normal way of doing it like what I did in the for loop?

Thanks in advance

Hi,

You can set dimensions to 1 so that they will be broadcasted:

y = y.view(1, 3, 1, 1)
out = x * y
1 Like

Thanks a lot :slight_smile:
By the way cant I directly use y.view(1,3,1,1) in the multiplication ?
Whats the difference between view() and expand()?

Yes you can do x * y.view(1, 3, 1, 1).
expand allows you to repeat a tensor along a dimension of size 1. view changes the size of the Tensor without changing the number of elements in it.

1 Like