Next: , Previous: , Up: Data Classes   [Contents][Index]

6.2.7 Ranges

A range is a variable that combines two values. Ranges are designed for indicating the start and end of index ranges in subscripts (Range Subscripts), but can be used to hold any kind of data. A range variable is defined as follows:

r = (r1:r2)

In this example, the variables r1 and r2 are the "start" and the "end" of the range, respectively. The only operations that can be performed on ranges other than scalar ranges (see below) are assignment and extraction of elements.

A scalar range is a range that contains only scalars. For scalar ranges, a special notation is available for counting from the end of the index range. In either field of a scalar range, expr stands for "count expr from the beginning of the index range", and * - expr stands for "count expr backwards from one beyond the end of the index range". For instance, if one-dimensional array x has ten elements, then x(3:5) selects the elements with indices 3, 4, and 5, and x(3:*-3) selects the elements with indices 3, 4, 5, 6, and 7. A single asterisk * in either field is equivalent with * - 1.

If only one field is specified but this field contains a * or * - expr expression, then the variable is treated as a range variable. A single asterisk * indicates the full range and is equivalent to (0:*). The * - expr notation is equivalent to a range with both fields equal to the specified one. Such a range selects only a single element. When used inside a subscript, the parentheses can be left off, and two more fields may be added to the range (Range Subscripts).

You can refer to the first two fields of a range variable by appending a subscript 0 (for the first field) or 1 (for the last field) between parentheses (). For instance, if r is the range (10:20), then r(0) is equal to 10 and r(1) is equal to 20. If the selected field contains a * - expr entry, then expr is returned. For instance, if r = (10:*-5), then r(1) yields 5.

You can assign new values to the first two fields of a range variable, but you cannot change the field’s format from ordinary to * or the other way around: you have to replace the whole range to achieve that. For instance, if r = (10:*-5), then r(1) = 3 changes the value of r to (10:*-3). To change to (10:20), do r = (10:20). Addition and subtraction involving ranges act to shift the range over the indicated amount. For instance, if r = (10:*-5), then r + 2 yields (12:*-3). Multiplication and division act on each of the range ends separately, so 2*r yields (20:*-10).

Next: , Previous: , Up: Data Classes   [Contents][Index]