What's the fastest way to slice a portion of a tensor to another in PyTorch?

Viewed 69

I have three tensors as shown below:

a = tensor([[5, 2, 3, 24],
        [8, 66, 7, 89],
        [9, 10, 1, 12]])

b = tensor([[10, 22, 13, 1],
            [35, 6, 17, 3],
            [11, 13, 5,8]])

c = tensor([[0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0,0]])

I want to chnage c values using this formula: Note that the last values (column) in c are not changed at this point.

c[:,:-1]= a[:,:-1] -a[:, 1:] - b[:, 1:] 

This means I will have

c = tensor([[5-2-22, 2-3-13, 3-24-1, 0],
            [8-66-6, 66-7-17, 7-89-3, 0],
            [9-10-13, 10-1-5, 1-12-8,0]])

>>>  c = tensor([[-19, -14, -22, 0],
                 [-64, 42, -85, 0],
                 [-14, 4, -19,0]])

Finally, to change the last column, I want to use c[:, -1] = b[:, -1] - 1

And my final tensor will look like this:

c = tensor([[-19, -14, -22, 0],
            [-64, 42, -85, 2],
            [-14, 4, -19,7]])
1 Answers

I think the fact that you are "overriding" the elements of c is causing you errors. Try creating c "from scratch", by concatenating its two parts:

c = torch.cat([a[:,:-1] -a[:, 1:] - b[:, 1:], 
               b[:, -1:] - 1], dim=-1)
Related