Find indices with value (zeros)

I have a 1D Variable (LongTensor) and i want to find the indices of the elements with a given value (zero). Is there a way to do this efficiently in PyTorch?

For instance, in order to get the indices of non-zero elements, i do this:

non_zeros = torch.nonzero(lengths_c.view(-1).data).squeeze()

I need the opposite of this (indices of zero elements).

5 Likes

(x != 0).nonzero()

2 Likes

I think it would be (x == 0).nonzero() instead of (x != 0).nonzero(). The last one is the same as x.nonzero().

10 Likes

@Nicolas_Beaudoin-Gag How can we use output of nonzero() function as index for accessing data from a tensor min_dist_sort (torch.DoubleTensor) which is torch.Size([9567, 4]). It has sorted distance in each column. It has zeros, I’m looking for minimum non-zero distance in each column. Hence, I’m doing the following (where ind some column number).

min_dist_sort[(torch.nonzero(min_dist_sort[:,ind]>0))[0],ind]

When I do this, I get the below error message.

TypeError: Performing basic indexing on a tensor and encountered an error indexing dim 0 with an object of type torch.LongTensor. The only supported types are integers, slices, numpy scalars, or if indexing with a torch.LongTensor or torch.ByteTensor only a single Tensor may be passed.

I’m not able to understand what the problem might be. Any suggestions here. Thank you.

6 Likes

hi,
I want to find the location of specific value in 3 dimention in pytorch. I used in2sub function in Matlab. Do you know what is the best option in Pytorch?

Would this answer from the other post work?

many thanks for your reply.
i should use torch.nonzero . I think it is the same as you recommend.