MATLAB Function Reference
find

Find indices and values of nonzero elements

Syntax

• ```indices = find(X)
indices = find(X, k)
indices = find(X, k, 'first')
indices = find(X, k, 'last')
[i`,`j] = find(...)
[i`,`j`,`v] = find(...)
```

Description

```indices = find(X) ``` returns the linear indices corresponding to the nonzero entries of the array `X`. If none are found, `find` returns an empty, 0-by-1 matrix. In general, `find(X)` regards `X` as `X(:)`, which is the long column vector formed by concatenating the columns of `X`.

`indices = find(X, k)` or `indices = find(X, k, 'first')` returns at most the first `k` indices corresponding to the nonzero entries of `X`. `k` must be a positive integer, but it can be of any numeric data type.

`indices = find(X, k, 'last')` returns at most the last `k` indices corresponding to the nonzero entries of `X`.

```[i,j] = find(...) ``` returns the row and column indices of the nonzero entries in the matrix `X`. This syntax is especially useful when working with sparse matrices. If `X` is an N-dimensional array with N > 2, `j` contains linear indices for the dimensions of `X` other than the first.

```[i,j,v] = find(...) ``` returns a column vector `v` of the nonzero entries in `X`, as well as row and column indices.

Examples

• ``````X = [1 0 4 -3 0 0 0 8 6];
``````indices = find(X)
``````

returns linear indices for the nonzero entries of `X`.

• ```indices =

1     3     4     8     9
```

You can use a logical expression to define `X`. For example,

• ```find(X > 2)
```

returns linear indices corresponding to the entries of `X` that are greater than 2.

• ```ans =

3     8     9
```

The following commands

• ``````X = [3 2 0; -5 0 7; 0 0 1];
````[i,j,v] = find(X)`
```

return

• ```i =

1
2
1
2
3
```

a vector of row indices of the nonzero entries of `X`,

• ```j =

1
1
2
3
3
```

a vector of column indices of the nonzero entries of `X`, and

• ```v =

3
-5
2
7
1
```

a vector containing the nonzero entries of `X`.

Some operations on a vector

• ```x = [11  0  33  0  55]';
find(x)

ans =

1
3
5

find(x == 0)

ans =

2
4

find(0 < x & x < 10*pi)

ans =

1
```

For the matrix

• ```M = magic(3)

M =

8     1     6
3     5     7
4     9     2

find(M > 3, 4)
```

returns the indices of the first four entries of `M` that are greater than 3.

• ```ans =

1
3
5
6
```

If `X` is a vector of all zeros, `find(X)` returns an empty, 0-by-1 matrix. For example,

• ```indices = find([0;0;0])

indices =

Empty matrix: 0-by-1
```

`nonzeros`, `sparse`, `colon`, logical operators (elementwise and short-circuit), relational operators, `ind2sub`