How to add value to tensor multiple times by index

Hi all.

Example:

x = torch.zeros(10)
x
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

indices = torch.tensor([1,1,3,3,3])

and I want to add value by index

x[indices] += 1

I get this

x
tensor([0., 1., 0., 1., 0., 0., 0., 0., 0., 0.])

But I want to get

x
tensor([0., 2., 0., 3., 0., 0., 0., 0., 0., 0.])

May be this impossible ?

Try doing like this:

x = torch.zeros(10)
indices = torch.tensor([1,1,3,3,3])
x.scatter_add_(0, indices, torch.ones_like(indices, dtype=torch.float32))
1 Like

Thank you. Its really works.
But how make it on 2d tensor ?
Now I do it with double cycle โ€˜forโ€™. Very slow.
Is it possible to add values โ€‹โ€‹to a tensor using broadcast?

x = torch.zeros(5, 5)
x
tensor([[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.]])
indices = torch.tensor([[2, 1],
                        [2, 1],
                        [2, 1],
                        [1, 1],
                        [1, 1]
                       ], 
                       dtype=torch.int)

And need to broadcast add value by each index

x[indices] += 1

it should turn out like this

x
tensor([[0., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 3., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.]])

Maybe you know how to do this without cycles?