pythonpytorch

Move elements up in a one dimensional torch tensor


If I have a torch tensor of the form:

[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

.roll simply moves the elements down

[6.0, 1.0, 2.0, 3.0, 4.0, 5.0]

I want it to roll the other way resulting in

[2.0, 3.0, 4.0, 5.0, 6.0, 1.0] 

(in fact, the last element will be zero'd in this particular case)

.inverse does a full reverse.

What are my options?


Solution

  • import torch
    ten = torch.Tensor([1, 2, 3, 4, 5, 6)
    
    
    ten.roll(-1, 0)
    

    The examples in the documentation of .roll() has a scenario just like yours.

    The link: https://docs.pytorch.org/docs/stable/generated/torch.roll.html

    And the example:

    >>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2)
    >>> x
    tensor([[1, 2],
            [3, 4],
            [5, 6],
            [7, 8]])
    
    >>> torch.roll(x, -1, 0)
    tensor([[3, 4],
            [5, 6],
            [7, 8],
            [1, 2]])