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?