How to calculates differences between adjacent elements

I want to calculate the differences between adjacent elements of a tensor X in 1 D.
e.g if my tensor has a dimension of BxC where B is batch size and C is a channel.
function diff(X) should outputt [X(2)-X(1) X(3)-X(2) ... X(c)-X(c-1)].
How can I do it in pytorch?

This code should work to compute the difference in the C dimension:

B, C = 10, 5
x = torch.arange(B * C).view(B, C)
result = x[:, 1:]  - x[:, :-1]
1 Like