hjsg1010
hjsg1010

Reputation: 173

Add two torch tensor list

I want to add two PyTorch tensors together, for example, let

a = tensor([[1., 1., 2.],
            [1., 1., 2.],
            [1., 1., 2.],
            [1., 1., 2.],
            [1., 1., 2.],
            [1., 1., 2.]])

b = tensor([[4., 5., 6., 7., 8., 9.],
            [4., 5., 6., 7., 8., 9.],
            [4., 5., 6., 7., 8., 9.],
            [4., 5., 6., 7., 8., 9.],
            [4., 5., 6., 7., 8., 9.],
            [4., 5., 6., 7., 8., 9.]])

And I would like the resulting tensor c to be:

c = tensor([[5., 6., 8., 8., 9., 11.],
            [5., 6., 8., 8., 9., 11.],
            [5., 6., 8., 8., 9., 11.],
            [5., 6., 8., 8., 9., 11.],
            [5., 6., 8., 8., 9., 11.],
            [5., 6., 8., 8., 9., 11.]])

Note: b.shape[1] is always a multiple of a.shape[1].

is there any better way than the solution below solution?

fin =  torch.Tensor()
for i in range(int(b.shape[1]/a.shape[1])):
    target = b[:,batch*i:batch*(i+1)]
    temp = torch.add(target, a)
    fin = torch.cat([fin, temp], dim =1)
c = fin

Upvotes: 0

Views: 834

Answers (1)

Ivan
Ivan

Reputation: 40768

You can repeat the columns of a to match the shape of b with torch.Tensor.repeat, then add the resulting tensor to b:

>>> b + a.repeat(1, b.size(1)//a.size(1))
tensor([[ 5.,  6.,  8.,  8.,  9., 11.],
        [ 5.,  6.,  8.,  8.,  9., 11.],
        [ 5.,  6.,  8.,  8.,  9., 11.],
        [ 5.,  6.,  8.,  8.,  9., 11.],
        [ 5.,  6.,  8.,  8.,  9., 11.],
        [ 5.,  6.,  8.,  8.,  9., 11.]])

Upvotes: 1

Related Questions