Inverse of nonzero()?

Looks like nonzero on a 2d tensor will return the coordinates of the non-zero elements? Is there a function which can take these coordinates, and a list of values, and recreate the original tensor?

You could use the following code:

x = torch.empty(5, 5).random_(3)
idx = x.nonzero()
y = torch.zeros(5, 5)
y[idx[:,0], idx[:,1]] = x[idx[:, 0], idx[:, 1]]

I’m not sure, if this issue was already solved, as x[x.nonzero()] seems not to be supported at the moment.


This works great. Thanks! :slight_smile:

1 Like