The WHERE function can be used to select array elements that meet certain conditions. For example, the statement:

data[WHERE(data LT 0, /NULL)] = -1

sets all negative elements of data to -1 without changing the positive elements. The result of the function, WHERE(data LT 0), is a vector composed of the subscripts of the negative elements of data. Using this vector as a subscript changes only the negative elements.

Tip: The NULL keyword forces the WHERE function to return !NULL if there are no matches. Since using !NULL as a subscript is quietly ignored, this allows the above line of code to execute successfully regardless of whether there are any values that meet the condition. For example, any values that are less than zero will be set to -1. If there are no values less than zero, then the data values will remain unchanged and execution continues.

Similarly, the WHERE function can be used to select elements of an array using expressions similar to A[WHERE(A GT 0)], which results in a vector composed only of the elements of A that are greater than 0.

The following statements create and display a 5x5 identity matrix, which consists of ones along a diagonal, and zeros everywhere else:

A = FLTARR(5, 5)
A[INDGEN(5) * 6] = 1
PRINT, A

The following statement sets elements of A with values of zero or less to -1:

A[WHERE(A LE 0, /NULL)] = -1
PRINT, A

In this example, assume that the vector data contains data elements and that a data drop-out is denoted by a negative value. In addition, assume that there are never two or more adjacent drop-outs. The following statements replace all drop-outs with the average of the two adjacent good points:

; Subscript vector of drop-outs.
bad = WHERE(data LT 0, /NULL)

; Replace drop-outs with average of previous and next point.