Reputation: 1
I want to ask a question about torch calculation that if I only want to subtract the elements on the diagonal of the matrix without changing the elements in the remaining positions, is there any way to achieve it?
Upvotes: 0
Views: 29
Reputation: 407
One way to do this is by getting the diagonal, doint the required operation on its elements and replacing the original one. Example code:
x = torch.rand(3, 3)
#get the original diagonal and for example substract 3
replaced_diag = x.diagonal() - 3
#replace the original diagonal
x.diagonal().copy_(replaced_diag)
For reference look at this: Replace diagonal elements with vector in PyTorch
Upvotes: 1