Best way to obtain first occurance in a tensor

Hey everyone,

could someone tell me the best way to get the indices of the first occurrences in a tensor along a specific dimension? By occurrence I mean the indices where the tensor is e.g. larger than a specific value:

For example, consider

my_tensor = torch.rand(10, 100)
my_value = 0.5

ind = (my_tensor < my_value) # Boolean mask whether the values are < 0.5

How do I obtain the first occurrence where ind == 1 along the dimension -1 (in a (10, 1) tensor) ?
For example, ind.nonzero() returns all non-zero values and does not keep the dimensions…

Thanks a lot!

1 Like

Hi Michael,

In my shallow view, the .nonzero operation cannot returns the keepdim=True version, because it cannot guarantee each dimension has the same number of elements that fit the nonzero condition, so it performs reduction to 1D and return positions.

But you could get the first occurrence by iteration like this:

next(x for x in nz_ind if x[0] > 0)

to get the first nonzero value in dim1.

bump. Is there a better answer for this in 2021?