How to get index of non-zero values for every row in a matrix pytorch

I want to return a dense tensor of the non-zero indices for each row. For example, given the tensors:


Should return


What do you want to do accomplish ?
The output you gave as an example is not a tensor, as it does not have the same number of elements in each “row”.

You can try torch.nonzero(x), or (meaning ‘not equal’).
One of the two solutions will probably suit your needs.

1 Like

One way to accomplish this is to do:

# x is a tensor

Docs for reference

Hello, is there a way to obtain indices of nonzero values such that they are differentiable?