Arrays and the FOR Statement

Arrays — collections of numbers or vectors — are among the most important data types in scientific work. IDL makes array manipulation very easy.

There are a number of ways to define an array. "fltarr(n)" is a function that returns an array of n floating point numbers, all set to 0.0. ("intarr" does the same, only with integers, set to 0.) "findgen(n)" is particularly useful; it gives an array of numbers that go 0.0, 1,0, . . . n-1.0.

You can operate on arrays directly with most IDL functions and operators. The operation affects each element of the array individually.

The best way to visualize some larger arrays is to plot them. These statements instruct IDL to do a plot of one period of the cosine function. Notice how you use "findgen" to produce a number of equally spaced values for the x axis; in this case, 31 different points that start at 0.0 and end at 2π.

And here is what the default plot produces:

Say you want to "rectify" the cosine wave, setting it to 0 where it is negative. The "where" function is IDL's tool to manipulate arrays according to conditions.

This gives:

IDL has functions which retrieve things like the maximum or minum values in an array, and the total of all its elements. Note that the same can be accomplished (less efficiently) by using a "for" loop to examine each element individually.

Note, here, how "r[i]" stands for the number that is the i'th element of the array r. Also note that in IDL, arrays start from a 0'th element. If an array r has n elements, it's elemenst are r[0], r[1], . . . , r[n-1]. So r[n] is out of range, and will cause an error.

With arrays in IDL, the for loop is not the best way to go, but loops are still very basic programming structures which come in handy often. Here is an example program to calculate integer powers of a number. Of course, IDL does this easily, by "x^n" and n does not even have to be an integer. But it's a good illustration.

When run, it does:

If you need to have more than one statement in a for loop, use "for . . . begin" to start the loop, and end with "endfor".


Taner Edis
Home
Last modified: November 8, 2006