# Reobtain sorted tensor from argsort

**URL:** <https://discuss.pytorch.org/t/reobtain-sorted-tensor-from-argsort/75008>\
**Category:** Uncategorized\
**Created:** [April 1, 2020, 1:44pm UTC](https://discuss.pytorch.org/t/reobtain-sorted-tensor-from-argsort/75008 "2020-04-01T13:44:13Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ymentha14](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ymentha14/32/22199_2.png) [@ymentha14](https://discuss.pytorch.org/u/ymentha14)\
**Post date:** [April 1, 2020, 1:44pm UTC](https://discuss.pytorch.org/t/reobtain-sorted-tensor-from-argsort/75008/1 "2020-04-01T13:44:13Z")

</div>

Hi,

I am looking for a way to recover the sorted version of a matrix from its argsort indexes in an efficient (pytorch friendly) way:

example:

```auto
k = tensor([[2, 9, 3],
             [8, 0, 0]])
sorted_k,indx = k.sort()

```

but running `k[indx]` leads to an error as the shape don’t match instead of returning `sorted_k`. My best version so far is  
`torch.cat([row[ind].unsqueeze(0) for ind,row in zip(indx,k)])`  
But since it involves a for loop, big computation get very slow as I run it. Is there a way to do better?  
[Related topic](https://discuss.pytorch.org/t/mapping-tensor-based-on-corresponding-index-tensor/53307)  
Thanks for your help!

---

<div class="post-metadata">

**Author:** ![LeviViana](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/leviviana/32/9548_2.png) [@LeviViana](https://discuss.pytorch.org/u/LeviViana)\
**Post date:** [April 1, 2020, 2:13pm UTC](https://discuss.pytorch.org/t/reobtain-sorted-tensor-from-argsort/75008/2 "2020-04-01T14:13:02Z")

</div>

I’m not sure I got your point. If you want to know how to use the indexes to sort a tensor, then this snippet could help:

```python
import torch
k = torch.tensor([[2, 9, 3],
             [8, 0, 0]])
sorted_k, indx = k.sort()
sorted_k_again = k.gather(1, indx)
sorted_k_again.equal(sorted_k) # <- prints True

```

> [@ymentha14](#):
>
> I am looking for a way to recover the sorted version of a matrix from its argsort indexes

`sorted_k` is what you want, if I get this right.

---

<div class="post-metadata">

**Author:** ![ymentha14](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ymentha14/32/22199_2.png) [@ymentha14](https://discuss.pytorch.org/u/ymentha14)\
**Post date:** [April 3, 2020, 1:28pm UTC](https://discuss.pytorch.org/t/reobtain-sorted-tensor-from-argsort/75008/3 "2020-04-03T13:28:11Z")

</div>

That’s exactly it. Thank you a lot!
