find

Finds the indices of nonzero elements.

Category: Language Fundamentals > Operators and Elementary Operations

Syntax

k = find(X)

Returns the linear indices of the nonzero elements of X.

k = find(X, n)

Returns only the first n indices.

k = find(X, n, 'last')

Returns the last n indices.

[row, col] = find(___)

Returns row and column subscripts.

[row, col, v] = find(___)

Also returns the nonzero values.

Description

find(x > 3) lists the positions where a condition holds, in increasing order of linear index (column-major). Use it with n to locate the first match: find(x > 3, 1).

The result is empty when no element qualifies, so check isempty(k) before using it as an index. To merely test for matches, any is simpler and faster.

Input arguments

X
Numeric or logical array, usually the result of a comparison such as x > 3.
n
Maximum number of indices to return.

Output arguments

k
Index vector. It is a row if X is a row vector, otherwise a column. It is empty when nothing matches.
row, col
Subscripts of the nonzero elements.
v
Values of the nonzero elements.

Example

x = [0 3 0 5 7];
find(x)
find(x > 3)
find(x, 1, 'last')
[r, c] = find([0 1; 1 0])
Output
ans = 1×3

     2     4     5
ans = 1×2

     4     5
ans = 5
r = 2×1

     2
     1
c = 2×1

     1
     2

See also

any all sort nnz ismember