Dynamically creating variables in a program

There are situations where it may be useful to create variables at runtime in an IDL program, taking the variable names from a string array. Though there are a couple ways of doing this, I’d like to use SCOPE_VARFETCH here, elaborating on an example found on its Help page.

I want to read, into individual variables, the data from all the PNG files in IDL’s examples/data directory (even though there are better ways to do this in IDL 8; e.g., with a list). Here’s how I can get the paths to these files:

IDL> start_dir = filepath('', subdirectory=['examples','data'])
IDL> ext = '.png'
IDL> png_files = file_search(start_dir, '*'+ext)

I intend to make an eponymous variable from the base name of each file:

IDL> varnames = file_basename(png_files, ext) ; a string array
IDL> print, varnames
africavlc afrpolitsm avhrr mineral moon_landing rockland shifted_endocell

Now loop through the files, reading them with READ_PNG into (here’s the trick) named variables created using SCOPE_VARFETCH:

IDL> for i=0, n_elements(png_files)-1 do $
>    (scope_varfetch(varnames[i], /enter, level=1)) = read_png(png_files[i])

Note the use of enclosing parentheses to group the output from the SCOPE_VARFETCH function. This is a legal, but uncommon, syntax in IDL (and may be worth its own blog post). I’m also choosing not to read the color tables from the files that have them.

Examine the results:

IDL> help, names='*'
AFRICAVLC       BYTE      = Array[540, 560]
AFRPOLITSM      BYTE      = Array[600, 600]
AVHRR           BYTE      = Array[720, 360]
EXT             STRING    = '.png'
I               INT       =        7
MINERAL         BYTE      = Array[288, 216]
MOON_LANDING    BYTE      = Array[300, 300]
PNG_FILES       STRING    = Array[7]
ROCKLAND        BYTE      = Array[3, 320, 461]
SHIFTED_ENDOCELL
                BYTE      = Array[615, 416]
START_DIR       STRING    = '/usr/local/exelis/idl82/examples/data/'
VARNAMES        STRING    = Array[7]

Another technique uses EXECUTE, though SCOPE_VARFETCH has the advantage of working in the IDL Virtual Machine, whereas EXECUTE does not.

About these ads

About Mark

I solve scientific programming and visualization problems with IDL.
This entry was posted in data access, language and tagged , , , , . Bookmark the permalink.

One Response to Dynamically creating variables in a program

  1. David Fanning says:

    Oh, dear. Opening Pandora’s Box here. I’ll forward the e-mails from confused newbies to you. :-)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s