FIND Find Non-zero Elements of An Array

Section: Array Generation and Manipulations

Usage

Returns a vector that contains the indicies of all non-zero elements in an array. The usage is
   y = find(x)

The indices returned are generalized column indices, meaning that if the array x is of size [d1,d2,...,dn], and the element x(i1,i2,...,in) is nonzero, then y will contain the integer

The second syntax for the find command is

   [r,c] = find(x)

which returns the row and column index of the nonzero entries of x. The third syntax for the find command also returns the values

   [r,c,v] = find(x).

This form is particularly useful for converting sparse matrices into IJV form.

Example

Some simple examples of its usage, and some common uses of find in FreeMat programs.
--> a = [1,2,5,2,4];
--> find(a==2)
ans = 
  <uint32>  - size: [2 1]
 
Columns 1 to 1
 2  
 4  

Here is an example of using find to replace elements of A that are 0 with the number 5.

--> A = [1,0,3;0,2,1;3,0,0]
A = 
  <int32>  - size: [3 3]
 
Columns 1 to 3
 1  0  3  
 0  2  1  
 3  0  0  
--> n = find(A==0)
n = 
  <uint32>  - size: [4 1]
 
Columns 1 to 1
 2  
 4  
 6  
 9  
--> A(n) = 5
A = 
  <int32>  - size: [3 3]
 
Columns 1 to 3
 1  5  3  
 5  2  1  
 3  5  5  

Incidentally, a better way to achieve the same concept is:

--> A = [1,0,3;0,2,1;3,0,0]
A = 
  <int32>  - size: [3 3]
 
Columns 1 to 3
 1  0  3  
 0  2  1  
 3  0  0  
--> A(A==0) = 5
A = 
  <int32>  - size: [3 3]
 
Columns 1 to 3
 1  5  3  
 5  2  1  
 3  5  5  

Now, we can also return the indices as row and column indices using the two argument form of find:

--> A = [1,0,3;0,2,1;3,0,0]
A = 
  <int32>  - size: [3 3]
 
Columns 1 to 3
 1  0  3  
 0  2  1  
 3  0  0  
--> [r,c] = find(A)
r = 
  <uint32>  - size: [5 1]
 
Columns 1 to 1
 1  
 3  
 2  
 1  
 2  
c = 
  <uint32>  - size: [5 1]
 
Columns 1 to 1
 1  
 1  
 2  
 3  
 3  

Or the three argument form of find, which returns the value also:

--> [r,c,v] = find(A)
r = 
  <uint32>  - size: [5 1]
 
Columns 1 to 1
 1  
 3  
 2  
 1  
 2  
c = 
  <uint32>  - size: [5 1]
 
Columns 1 to 1
 1  
 1  
 2  
 3  
 3  
v = 
  <int32>  - size: [5 1]
 
Columns 1 to 1
 1  
 3  
 2  
 3  
 1