LOC Function

LOC (matrix) ;

The LOC function finds nonzero elements of a matrix. It creates a $1 \times n$ row vector, where $n$ is the number of nonzero elements in the argument matrix. 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).

For example, consider the following statements:

a = {1 0 2 3 0};
b = loc(a);
print b;

Because the first, third, and fourth elements of a are nonzero, these statements result in the row vector shown in Figure 24.195:

Figure 24.195: Location of Nonzero Elements

b
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, the following statements create a matrix y that contains the rows of x that have a positive element in the diagonal of x:

x = {1  1  0,
     0 -2  2,
     0  0  3};
y = x[loc(vecdiag(x)>0), ];
print y;

Figure 24.196: Rows with Positive Diagonal Elements

y
1 1 0
0 0 3