Torch.gather from 1D array using 2D indices
I have an nx1 tensor and an nxm tensor. I want to gather values from the nx1 tensor using the nxm tensor.
For example
for input tensor([1, 2, 3, 4]) and
index tensor([[0, 3], [2, 1],[1, 3], [2,3]])
output should be
tensor([[1, 4], [3, 2], [2,4], [3,4])

The indices are in the 2D matrix and the values are to be gathered from the 1D list.
How to use torch.gather/ or any torch tensor function for this purpose?
My following code gives error
t = torch.tensor([[1, 2, 3, 4]])
ind = torch.tensor([[0, 3], [2, 1],[1, 3], [2,3]])
torch.gather(t, 0, ind)

RuntimeError: index 2 is out of bounds for dimension 0 with size 1

Edit:
You can do simple indexing to achieve this output.
t[ind]

Is this the best way to do this. I assume this involves broadcasting the input array.
Edit
Using t[ind] in forward pass is resulting in the error
/pytorch/aten/src/ATen/native/cuda/IndexKernel.cu:84: operator(): block: [430,0,0], thread: [97,0,0] Assertion `index &gt;= -sizes[i] &amp;&amp; index &lt; sizes[i] &amp;&amp; &quot;index out of bounds&quot;` failed.

When I try to print tensors in the forward pass, no output is shown after the t[ind] operation. Which makes sense as getitem is not a differentiable operation for the loss to propagate.
So there is a valid use case in using gather over getitem.

If you want to use torch.gather:
torch.gather(t.expand(4, -1), 1, ind)

