Previous Application Programming: Structures Next

Arrays of Structures

An array of structures is simply an array in which each element is a structure of the same type. The referencing and subscripting of these arrays (also called structure arrays) follow the same rules as simple arrays.

Creating an Array of Structures

The easiest way to create an array of structures is to use the REPLICATE function. The first parameter to REPLICATE is a reference to the structure of each element. Using the example in Examples of Structure References and assuming the STAR structure has been defined, an array containing 100 elements of the structure is created with the following statement:

cat = REPLICATE({star}, 100)  

Alternatively, since the variable A contains an instance of the structure STAR, then

cat = REPLICATE(A, 100)  

Or, to define the structure and an array of the structure in one step, use the following statement:

cat = REPLICATE({star, name:'', ra:0.0, dec:0.0, $  
    inten:FLTARR(12)}, 100)  

The concepts and combinations of subscripts, subscript arrays, subscript ranges, fields, nested structures, etc., are quite general and lead to many possibilities, only a small number of which can be explained here. In general, any structures that are similar to the examples above are allowed.

Examples of Arrays of Structures

This example uses the above definition in which the variable CAT contains a star catalog of STAR structures.

;Set the name field of all 100 elements to "EMPTY."  
cat.name = 'EMPTY'  
  
;Set the i-th element of cat to the contents of the star structure.  
cat[I] = {star, 'BETELGEUSE', 12.4, 54.2, FLTARR(12)}  
  
;Store 0.0 into cat[0].ra, 1.0 into cat[1].ra, ..., 99.0 into   
;cat[99].ra  
cat.ra = INDGEN(100)  
  
;Prints name field of all 100 elements of cat, separated by commas   
;(the last field has a trailing comma).  
PRINT, cat.name + ','  
  
;Find index of star with name of SIRIUS.  
I = WHERE(cat.name EQ 'SIRIUS')  
  
;Extract intensity field from each entry. Q will be a 12 by 100   
;floating-point array.  
Q = cat.inten  
  
;Plot intensity of sixth star in array cat.  
PLOT, cat[5].inten  
  
;Make a contour plot of the (7,46) floating-point array ;taken from   
;months (2:8) and stars (5:50).  
CONTOUR, cat[5:50].inten[2:8]  
  
;Sort the array into ascending order by names. Store the result   
;back into cat.  
cat = cat(SORT(cat.name))  
  
;Determine the monthly total intensity of all stars in array.   
;monthly is now a 12-element array.  
monthly = cat.inten # REPLICATE(1,100)  

  IDL Online Help (March 06, 2007)