# find

Finding indices of non-zero elements

### [r, c, x] = find(X)

• X can be a scalar, vector, or multidimensional array.
• v is a vector containing linear indices of non-zero elements of X.
• r and c contain, respectively, the row and column indices of the non-zero elements. If X has more than 2 dimensions, X is first reshaped to a matrix with the same number of rows as the original X (see Example 3).
• X contains the non-zero elements such that x is equal to X(v).

### [r, c, x] = find(X, n)

• The same as the previous statements, except that only indices of the first n non-zero elements are returned.
• n should be a positive integer.

Example 1: Finding non-zero elements of a random matrix.

X=randi(2, 3, 4)-2
v=find(X)
X =
0.000   0.000   0.000   0.000
-1.000  -1.000  -1.000  -1.000
0.000  -1.000  -1.000  -1.000

v =
Columns 1 through 5:
2.000   5.000   6.000   8.000   9.000
Columns 6 through 7:
11.00   12.00

Example 2 Finding non-zero elements of a random matrix.

X=randi(6,3,4)-1
[r,c,x]=find(X)
X =
0.000   1.000   5.000   4.000
2.000   0.000   0.000   0.000
4.000   0.000   0.000   4.000

r =
2.000   3.000   1.000   1.000   1.000   3.000

c =
1.000   1.000   2.000   3.000   4.000   4.000

x =
2.000   4.000   1.000   5.000   4.000   4.000

Example 3 In this example, X has 3 dimensions, which is first reshaped to a matrix before finding indices of non-zero elements.

X=randi(6,3,4,2)-1
[r,c,x]=find(X)
X(:, :, 1) =

1.000   3.000   0.000   3.000
5.000   4.000   4.000   0.000
2.000   3.000   5.000   2.000

X(:, :, 2) =

0.000   4.000   1.000   0.000
0.000   5.000   0.000   3.000
1.000   1.000   0.000   1.000

r =
Columns 1 through 5:
1.000   2.000   3.000   1.000   2.000
Columns 5 through 10:
3.000   2.000   3.000   1.000   3.000
Columns 11 through 15:
3.000   1.000   2.000   3.000   1.000
Columns 16 through 17:
2.000   3.000

c =
Columns 1 through 5:
1.000   1.000   1.000   2.000   2.000
Columns 5 through 10:
2.000   3.000   3.000   4.000   4.000
Columns 11 through 15:
5.000   6.000   6.000   6.000   7.000
Columns 16 through 17:
8.000   8.000

x =
Columns 1 through 5:
1.000   5.000   2.000   3.000   4.000
Columns 6 through 10:
3.000   4.000   5.000   3.000   2.000
Columns 11 through 15:
1.000   4.000   5.000   1.000   1.000
Columns 16 through 17:
3.000   1.000