How can I operate on a tensor slice guided by a index group with repeated index inside?

When I try to operate a tensor guided by a index with repeated index, it would only responses to the last operation. For example:

A = torch.FloatTensor([1,2,3,4])
index = torch.LongTensor([1,2,1,2])
add_value = torch.FloatTensor([1,2,3,4])
A[index]+= add_value
# tensor([ 1.,  5.,  7.,  4.])

you can find that the output tensor came from [1, 2+3, 3+4, 4].
However, what I want to get is [1, 2+1+3, 3+2+4, 4].
What should I do?

tensor.scatter_add should yield this result:

A.scatter_add(0, index, add_value)
1 Like

Thank you! It works!