Previous Getting Started with IDL: Manipulating Data Next

Avoiding IF Statements for Performance

Programs with array expressions run faster than programs with scalars, loops, and IF statements. The following sections provide alternatives to using IF statements.

Summing to Avoid IF Statements

The first example adds all positive elements of array B to array A.

Using Array Operators and the WHERE Function

In the example below, each element of C is set to the square-root of A if A[I] is positive; otherwise, C[I] is set to minus the square-root of the absolute value of A[I].

Another method is to use the WHERE function to determine the subscripts of the negative elements of A and negate the corresponding elements of the result.

Example— Using Vector and Array Operations

Whenever possible, vector and array data should always be processed with IDL array operations instead of scalar operations in a loop. For example, consider the problem of flipping a 512 ´ 512 image. This problem arises because approximately half the available image display devices consider the origin to be the lower-left corner of the screen, while the other half recognize it as the upper-left corner.

The following example is for demonstration only. The IDL system variable !ORDER should be used to control the origin of image devices. The ORDER keyword to the TV procedure serves the same purpose.

A programmer without experience in using IDL might be tempted to write the following nested loop structure to solve this problem:

FOR I = 0, 511 DO FOR J = 0, 255 DO BEGIN  
  • Temporarily save pixel:
  • TEMP=IMAGE[I, J]  
    

     

  • Exchange pixel in same column from corresponding row at bottom.
  • image[I, J] = image[I, 511 - J]  
    image[I, 511-J] = temp  
    ENDFOR  
    

    A more efficient approach to this problem capitalizes on IDL's ability to process arrays as a single entity.

    At the cost of using twice as much memory, processing can be simplified even further by using the following statements:

    that reverses the array using subscript ranges and array-valued subscripts.

      IDL Online Help (March 06, 2007)