Multiplication of tensors

Hello, I would like to multiply tensor t1 = torch.tensor([1, 2, 3, 4, 5]) and t2 = torch.tensor([1, 2, 1]) in order to get result similar like from 1D kernel application: [1 * 1 + 2 * 2 + 3 * 1, 2 * 1 + 3 * 2 + 4 * 1, 3 * 1 + 4 * 2 + 5 * 1]. Can you give me advice, how to compute this case without any for loop?

Thank you. :slight_smile:

Hi Marek!

Use unfold() to generate the correct “slices” of t1:

>>> import torch
>>> torch.__version__
'1.9.0'
>>> t1 = torch.tensor([1, 2, 3, 4, 5])
>>> t2 = torch.tensor([1, 2, 1])
>>> t1.unfold (0, 3, 1) @ t2
tensor([ 8, 12, 16])

You could also use conv1d() if you unsqueeze() t1 and t2 to add
the required singleton dimensions.

Best.

K. Frank

1 Like