How to divide a batch of matrices by a batch of scalars?

Hi everyone,

I just have a general question. Let’s say I have a batch of matrices of shape matrices = [1000, 4, 8] and I have a batch of scalars scalars = [1000], how can I divide the i-th matrix in matrices with the i-th scalar in scalars?

I could see a potential way to use torch.stack but it’d be way too slow as I need the operation to be vectorized! I’m sure I’ve missed something here, any help is apprecitated! :slight_smile:

I’ve just tried this and I think I’ve done it. Can someone confirm this is correct?

x = torch.randn(1000, 4, 8)
y = torch.randn(1000)

xnew = x/y[:, None, None]

Yes, your approach should work fine and you could double check it with a defined examples, such as:

x = torch.arange(1, 5)[:, None, None].expand(-1, 4, 8).float()
y = torch.arange(1, 5).float()

xnew = x/y[:, None, None]
1 Like