# How do I index a 2-D matrix row wise?

I would like to index a 2-D matrix row-wise and re-assign values.

For example, first consider a 1-D vector case where we have three 1-D tensors `t1, indexes, t2` with the same shape. We can do this indexing and re-assignment as follows:

``````indexes = torch.tensor([0, 2, 1, 3])
t1 = torch.tensor([0.0, 0.0, 0.0, 0.0])
t2 = torch.tensor([0.1, 0.2, 0.3, 0.4])

t1[indexes] = t2
``````

Now, say that `t1, indexes, t2` are 2-D matrices instead of 1-D vectors and have the same shape `(R X C)`. I would like to do similar indexing as above for every row in these matrices where:

``````for i in range(R):
t1[i][indexes[i]] = t2[i]
``````

I would like to vectorize this operation instead of using a for loop. How do I do this?

`.scatter_` should work in this case:

``````indexes = torch.tensor([[0, 2, 1, 3],
[1, 0, 3, 2]])
t1 = torch.zeros_like(indexes).float()
t2 = torch.tensor([[0.1, 0.2, 0.3, 0.4],
[0.5, 0.6, 0.7, 0.8]])
t1.scatter_(1, indexes, t2)
``````
1 Like