Zeroing the diagonal of a matrix by multiplying by (1-I)

Viewed 28

I have a tensor, lets say like this:

tensor([[2.7183, 0.4005, 2.7183, 0.5236],
    [0.4005, 2.7183, 0.4004, 1.3469],
    [2.7183, 0.4004, 2.7183, 0.5239],
    [0.5236, 1.3469, 0.5239, 2.7183]])

And I want to zero its main diagonal by multiplying it by (1-I), meaning by 1 minus the identity matrix. How can I do this in pytorch?

Result of the example should be:

    tensor([[0.0000, 0.4005, 2.7183, 0.5236],
    [0.4005, 0.0000, 0.4004, 1.3469],
    [2.7183, 0.4004, 0.0000, 0.5239],
    [0.5236, 1.3469, 0.5239, 0.0000]])

I'm looking for a general case solution and not specific to the example I gave. Thanks!

2 Answers

torch.eye will be helpful for generating identity matrix

import torch

x = torch.tensor([[2.7183, 0.4005, 2.7183, 0.5236],
    [0.4005, 2.7183, 0.4004, 1.3469],
    [2.7183, 0.4004, 2.7183, 0.5239],
    [0.5236, 1.3469, 0.5239, 2.7183]],dtype=torch.float32)
y = 1-torch.eye(x.size()[0],dtype=torch.float32)  #only if x is square matrix
output = x*y

PyTorch has a built in function to do this inplace:

x.fill_diagonal_(0)

You can either apply this to your matrix directly, or if you really want 1 - I can apply it to a ones matrix:

1 - torch.eye(n)

# Alternatively
torch.ones(n,n).fill_diagonal_(0)
Related