Home | Categories | Alphabetical | Classes | All Contents | [ < ] | [ > ]

Use 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 inverting 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 image.  
   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:

FOR J = 0, 255 DO BEGIN 
 
   ;Temporarily save current row. 
   temp = image[*, J] 
 
   ;Exchange row with corresponding row at bottom. 
   image[*, J] = image[*, 511-J] 
 
   image[*, 511-J] = temp 
 
ENDFOR 

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

;Get a second array to hold inverted copy. 
image2 = BYTARR(512, 512) 
 
;Copy the rows from the bottom up. 
FOR J = 0, 511 DO image2[*, J] = image[*, 511-J] 

Even more efficient is the single line:

image2 = image[*, 511 - INDGEN(512)] 

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

Finally, using the built-in ROTATE function is quickest of all:

image = ROTATE(image, 7) 

Inverting the image is equivalent to transposing it and rotating it 270 degrees clockwise.


Home | Categories | Alphabetical | Classes | All Contents | [ < ] | [ > ]