# Access tensor value through index value stored in another tensor

For below code, How would I access the value of “x” for the index mentioned in “y”?
Output should be [[1,9,17],[4,12,20]].

x shape is "torch.Size([3,1,8]) and y shape is "torch.Size([2, 2]).

``````import torch
x= torch.tensor([[[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.]],

[[ 8.,  9., 10., 11., 12., 13., 14., 15.]],

[[16., 17., 18., 19., 20., 21., 22., 23.]]])

y=torch.tensor([[0,1],[0,4]])``````

Hi Cbd!

With a little fiddling around to get the indices in the right places, you
can use indexing;

``````>>> import torch
>>> torch.__version__
'1.9.0'
>>> x = torch.tensor([[[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.]],
...         [[ 8.,  9., 10., 11., 12., 13., 14., 15.]],
...         [[16., 17., 18., 19., 20., 21., 22., 23.]]])
>>> y = torch.tensor([[0,1], [0,4]])
>>> x[:, y[:, 0], y[:, 1]].T
tensor([[ 1.,  9., 17.],
[ 4., 12., 20.]])
``````

Best.

K. Frank

I just want the answer just passing the variable y as indexing like “torch.function(x,y)” because in real there are so many values in tensor “y” for indexing in tensor “x”. Is it possible by using some pytorch function or trick.

KFrank K. Frank
October 7

Hi Cbd!

cbd:

Output should be [[1,9,17],[4,12,20]].

With a little fiddling around to get the indices in the right places, you
can use indexing;

``````>>> import torch
>>> torch.__version__
'1.9.0'
>>> x = torch.tensor([[[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.]],
...         [[ 8.,  9., 10., 11., 12., 13., 14., 15.]],
...         [[16., 17., 18., 19., 20., 21., 22., 23.]]])
>>> y = torch.tensor([[0,1], [0,4]])
>>> x[:, y[:, 0], y[:, 1]].T
tensor([[ 1.,  9., 17.],
[ 4., 12., 20.]])

``````

Best.

K. Frank