Nonzero

torch_nonzero(self)

Arguments

self

(Tensor) the input tensor.

Note

[`torch_nonzero(..., as_tuple=False) <torch.nonzero>`] (default) returns a
2-D tensor where each row is the index for a nonzero value.

[`torch_nonzero(..., as_tuple=TRUE) <torch.nonzero>`] returns a tuple of 1-D
index tensors, allowing for advanced indexing, so `x[x.nonzero(as_tuple=TRUE)]`
gives all nonzero values of tensor `x`. Of the returned tuple, each index tensor
contains nonzero indices for a certain dimension.

See below for more details on the two behaviors.

nonzero(input, *, out=NULL, as_tuple=False) -> LongTensor or tuple of LongTensors

When as_tuple is FALSE (default):

Returns a tensor containing the indices of all non-zero elements of input. Each row in the result contains the indices of a non-zero element in input. The result is sorted lexicographically, with the last index changing the fastest (C-style).

If input has \(n\) dimensions, then the resulting indices tensor out is of size \((z \times n)\), where \(z\) is the total number of non-zero elements in the input tensor.

When as_tuple is TRUE:

Returns a tuple of 1-D tensors, one for each dimension in input, each containing the indices (in that dimension) of all non-zero elements of input .

If input has \(n\) dimensions, then the resulting tuple contains \(n\) tensors of size \(z\), where \(z\) is the total number of non-zero elements in the input tensor.

As a special case, when input has zero dimensions and a nonzero scalar value, it is treated as a one-dimensional tensor with one element.

Examples

if (torch_is_installed()) { torch_nonzero(torch_tensor(c(1, 1, 1, 0, 1))) }
#> torch_tensor #> 0 #> 1 #> 2 #> 4 #> [ CPULongType{4,1} ]