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?
Asked
Active
Viewed 28 times
1 Answers
1
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

dufrmbgr
- 397
- 1
- 11