Chapter Contents Previous Next
 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 ×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, the statements
```   a={1 0 2 3 0};
b=loc(a);
```
result in the row vector
```                B             1 row       3 cols    (numeric)

1         3         4
```
since the first, third, and fourth elements of A are nonzero. 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 statements
```   x={1  1  0,
0 -2  2,
0  0  3};
y=x[loc(vecdiag(x)>0),];
```
The result is
Y = X[{ 1 3},]
or the matrix
```                Y             2 rows      3 cols    (numeric)

1         1         0
0         0         3
```
since the first and third rows of X have positive elements on the diagonal of X.

The next example selects all positive elements of a column vector A:
```    a={0,
-1,
2,
0};
y=a[loc(a>0),];
```
The result is
Y = A[3,]
or the scalar
```                Y             1 row       1 col     (numeric)

2
```

 Chapter Contents Previous Next Top