Repeat tensor question

I was wondering how to repeat a 2D tensor

let’s say

a = [
 [x1, x2, x3],
 [y1, y2, y3]
]

to this tensor

[
  [x1,x1,x1,x2,x2,x2,x3,x3,x3],
  [y1,y1,y1,y2,y2,y2,y3,y3,y3]
]

I can’t implement this via torch.cat(),for now, I can only use torch.gather to achieve this, but it’s kind of complicated, is there any way easier?

You could use index_select with repeated indices.
It’s definitely not the most elegant solution, but maybe it’s a bit easier to use.

x = torch.Tensor([[0, 1, 2], [3, 4 ,5]])
indices = torch.LongTensor([0, 0, 0, 1, 1, 1, 2, 2, 2])
torch.index_select(x, 1, indices)

Let me know, if this was helpful or still a painful solution :wink:

Sure, it helps!, it’s definitely easier to use than gather
I think that was because I am new to Pytorch, and not familiar to the API.
Thank you so much for answering my stupid question :joy:

Another way, without creating an index tensor:

t = torch.Tensor(a)
t.view(-1, 1).repeat(1, 3).view(t.size(0), -1)
2 Likes

awesome solution! thank you !!:grin: