'Efficiently add numbers to the end of each dimension of a tensor

I have a tensor x of shape (n, 200). I want to make it shape (n, 218), by appending a tensor of 18 numbers to the end of every "row" of the current tensor. n varies based on the batch size, so I want a way to do this for any n.
As of right now, I have a working solution, but I was wondering if there is a built-in way to do this, I did not see anything in the documentation particularly. My method is:

import torch.nn.functional as F
x = F.pad(input = x, (0, 18, 0, 0)) # pad each tensor in dim 2 with 18 zeroes
for index in range(x.shape[0]): 
    x[index][-18] = nums_to_add # nums_to_add is a tensor with size (1,18)

This works just fine, but I was wondering if there is any easier way to do this, without first padding the zeroes.



Solution 1:[1]

torch.cat() is what you are looking for. Here is a snippet:

import torch
a = torch.randint(1,10,(3,4))
b =  torch.randint(1,10,(3,2))
print(a)
print(b)
a = torch.cat((a,b),axis=1) # axis should be one here
print(a)

Output

tensor([[2, 5, 3, 8],
        [3, 9, 5, 3],
        [9, 4, 9, 9]])
tensor([[6, 4],
        [1, 1],
        [8, 3]])
tensor([[2, 5, 3, 8, 6, 4],
        [3, 9, 5, 3, 1, 1],
        [9, 4, 9, 9, 8, 3]])

Now here is a similar example just used repeat to make it same shape in dim=0 so that we can concatenate it easily. (Trying to follow OP's suggestion exactly)

import torch
a = torch.randint(1,10,(5,200)) # shape(5,200)
b =  torch.randint(1,10,(1,18)).repeat((5,1)) # shape(5,18)
a = torch.cat((a,b),axis=1) # axis should be one here
print(a.shape) # (5,218)

The only tricky part of the above solution is the repeat() part (If you can say it complicated ...), which basically repeats this tensor along the specified dimensions. Check here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1