# Indexing a tensor with unique indices along each element of a batch

**URL:** <https://discuss.pytorch.org/t/indexing-a-tensor-with-unique-indices-along-each-element-of-a-batch/103447>\
**Category:** vision\
**Created:** [November 19, 2020, 11:12pm UTC](https://discuss.pytorch.org/t/indexing-a-tensor-with-unique-indices-along-each-element-of-a-batch/103447 "2020-11-19T23:12:08Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Pietro\_Cicalese](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/pietro_cicalese/32/27365_2.png) [@Pietro\_Cicalese](https://discuss.pytorch.org/u/Pietro_Cicalese)\
**Post date:** [November 20, 2020, 7:41pm UTC](https://discuss.pytorch.org/t/indexing-a-tensor-with-unique-indices-along-each-element-of-a-batch/103447/2 "2020-11-20T19:41:01Z")

</div>

This appears to have been solved [here.](https://discuss.pytorch.org/t/batched-index-select/9115) This is however not in-place as far as I can tell.

The solution:

```auto
def batched_index_select(input, dim, index):
    for ii in range(1, len(input.shape)):
        if ii != dim:
            index = index.unsqueeze(ii)
    expanse = list(input.shape)
    expanse[0] = -1
    expanse[dim] = -1
    index = index.expand(expanse)
    return torch.gather(input, dim, index)

```

If anyone can figure out an in-place solution it would be deeply appreciated, I will also keep trying and report back here if I make any progress.

---

_[View the full topic](https://discuss.pytorch.org/t/indexing-a-tensor-with-unique-indices-along-each-element-of-a-batch/103447)._
