How to set a tensor's value by index?

how to set a tensor’s value by index?
For example, we have a tensor a=[[0,0,0], [0,0,0], [0,0,0]],
and index=[[0,0], [1,1], [2,2]], values=[1,2,-1], how can a change a to [[1,0,0], [0,2,0], [0,0,-1]]?

I tied scatter but failed, could you also explain when we need scatter?

Hi Weikun!

Use pytorch’s tensor indexing.

Because values has shape [3] you will want the two index tensors that
you use to index into a to also have shape [3]. Then you can assign
values to the view into a obtained by indexing into a. Specifically:

>>> import torch
>>> torch.__version__
'1.12.0'
>>> a = torch.zeros (3, 3, dtype = torch.long)
>>> ind0 = torch.tensor ([0, 1, 2])
>>> ind1 = torch.tensor ([0, 1, 2])
>>> values = torch.tensor ([1, 2, -1])
>>> a[ind0, ind1] = values
>>> a
tensor([[ 1,  0,  0],
        [ 0,  2,  0],
        [ 0,  0, -1]])

Best.

K. Frank

Thank you very much! You really helped me a lot!! :smile: