Language Reference

LOC Function

finds nonzero elements of a matrix

LOC( matrix)

where matrix is a numeric matrix or literal.

The LOC function creates a 1 x n row vector, where n is the number of nonzero elements in the argument. Missing values are treated as zeros. The values in the resulting row vector are the locations of the nonzero elements in the argument (in row-major order, like subscripting). For example, consider the following statements:

  
    a={1 0 2 3 0}; 
    b=loc(a);
 
Because the first, third, and fourth elements of a are nonzero, these statements result in the following row vector:
  
                 B             1 row       3 cols    (numeric) 
  
                                 1         3         4
 

If every element of the argument vector is 0, the result is empty; that is, b has zero rows and zero columns.

The LOC function is useful for subscripting parts of a matrix that satisfy some condition.

For example, suppose you want to create a matrix y containing the rows of x that have a positive element in the diagonal of x. Specify the following statements:

  
    x={1  1  0, 
       0 -2  2, 
       0  0  3}; 
    y=x[loc(vecdiag(x)>0),];
 
Because the first and third rows of x have positive elements on the diagonal of x, the matrix y is as follows:
  
                 Y             2 rows      3 cols    (numeric) 
  
                                 1         1         0 
                                 0         0         3
 

The following example selects all positive elements of a column vector a:

  
     a={0, 
       -1, 
        2, 
        0}; 
    y=a[loc(a>0),];
 
The resulting output is as follows:
  
                 Y             1 row       1 col     (numeric) 
  
                                           2
 

Previous Page | Next Page | Top of Page