Moving Rows in Tensor

lst = [[0, 1, -4, 8],
         [2, -3, 2, 1],
         [5, -8, 7, 1]]

 torch.Tensor(lst)

This is a 4 x 3 matrix. How do swap first and second row to the following matrix?

lst = [[2, -3, 2, 1], 
        [0, 1, -4, 8],
        [5, -8, 7, 1]]

 torch.Tensor(lst)

you can do this with an index_copy. You can generate linear indices such as [0, 1, 2, 3] using torch.arange, and then swap 0 and 1. Then use these as indices to index_copy.

Alternatively, you can do something simpler too:

x = tlist[0].clone()
tlist[0] = tlist[1]
tlist[1] = x

1 Like