import torch # Create a 1-D tensor A = torch.tensor([5, 1, 3, 2, 4]) # Sort the tensor and get the indices idx = torch.argsort(A) # Print the sorted tensor and indices print(A[idx]) print(idx)
tensor([1, 2, 3, 4, 5]) tensor([1, 3, 2, 4, 0])
import torch # Create a 2-D tensor A = torch.tensor([[5, 1, 3], [2, 4, 7]]) # Sort the second row and get the indices idx = torch.argsort(A[1]) # Print the sorted row and indices print(A[:, idx[1]]) print(idx)
tensor([[3, 5, 1], [7, 2, 4]]) tensor([1, 0, 2])This method is a part of the PyTorch library.