Replacing tensro values with a list of index and corresponding features?

I’m currently trying to replace values AxBxC matrix with given array of indexes and corresponding values.

for example I have an index array [[0,1], [1,0], [3,4]] for a 6x6x4 matrix, with corresponding value [[1,1,1,1],[2,2,2,2],[3,3,3,3]]. I’d like to replace the values in the 6x6x4 matrix at [0,1,:], [1,0,:], and [3,4,:] with [1,1,1,1], [2,2,2,2] and [3,3,3,3]. extracting is possible with given indices, but not the other way around it seems

This should work:

A, B, C = 6, 6, 4
x = torch.zeros(A, B, C)
idx = torch.tensor([[0,1], [1,0], [3,4]])
val = torch.tensor([[1,1,1,1],[2,2,2,2],[3,3,3,3]]).float()

x[idx[:, 0], idx[:, 1]] = val
print(x)
> tensor([[[0., 0., 0., 0.],
           [1., 1., 1., 1.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.]],

          [[2., 2., 2., 2.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.]],

          [[0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.]],

          [[0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [3., 3., 3., 3.],
           [0., 0., 0., 0.]],

          [[0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.]],

          [[0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.]]])
1 Like

Thank you! I actually forgot to convert the tensor(in this case val) from numpy matrix, so that’s why it didn’t end up working haha.