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:

[0,1,1]
[1,0,0]
[0,0,1]
[0,1,0]

Should return

[1,2]
[0]
[2]
[1]

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 x.ne(0) (meaning ‘not equal’).
One of the two solutions will probably suit your needs.

One way to accomplish this is to do:

# x is a tensor
x.nonzero(as_tuple=True)[0]

Docs for reference

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