How to get a new tensor via repeating index for element times?

If I have a tensor [1,2,3,4], how can I get tensor [0, 1, 1, 2, 2, 2, 3, 3, 3, 3] as fast as possible?

A for-loop is very slow, but I haven’t find any relevant Pytorch API.

Can anyone provide a good way?

Generally for this kind of problem, you could use torch.repeat_interleave:

x = torch.arange(5)
torch.repeat_interleave(x, torch.tensor([1, 2, 3, 4, 5]), dim=0)

However, in your example, somehow a 0 is added at the beginning and the 4 is missing, so you might need to use torch.cat and a slicing operation.

Thank you very much! And I tested the efficiency of three methods:
Imgur