I have two tensors. For example -

a = torch.randn((500, 200, 10))
b = torch.randn((500, 5))

I have to concat each of b tensor to all elements of corresponding a tensor i.e., each 200 tensors of a[0] should get concatenated with b[0] - final dimension should be (500, 200, 15).

Without using explicit for loop, how can I achieve this in Pytorch efficiently?


1 Answer 1


For that, you should repeat b 200 times in the appropriate dimension this way:

c = torch.cat([a, torch.unsqueeze(b, 1).repeat(1, 200, 1)], dim=2)

As desired, the shape of the result is torch.Size([500, 200, 15])


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.