Yorick: Negative Index

Home Manual Packages Global Index Keywords Quick Reference |
### 2.3.6 Numbering a dimension from its last element Array index values are subtly asymmetric: An index of 1 represents the first element, 2 represents the second element, 3 the third, and so on. In order to refer to the last, or next to last, or any element relative to the final element, you apparently need to find out the length of the dimension. In order to remedy this asymmetry, Yorick interprets numbers less than 1 relative to the final element of an array. Hence, `x(1)` and `x(2)` are the first and second elements of `x`, while `x(0)` and `x(-1)` are the last and next to last elements, and so on. With this convention for negative indices, many Yorick programs can be written without the need to determine the length of a dimension:
    deriv = (f(3:0)-f(1:-2)) / (x(3:0)-x(1:-2));
computes a point-centered estimate of the derivative of a function `f` with values known at points `x`. (A better way to compute this derivative is to use the `pcen` and `dif` range functions described below. See section Rank preserving (finite difference) range functions.) In this example, the extra effort required to compute the array length would be slight:
    n = numberof(f);
    deriv = (f(3:n)-f(1:n-2)) / (x(3:n)-x(1:n-2));
However, using the negative index convention produces faster code, and generalizes to multi-dimensional cases in an obvious way. The negative index convention works for scalar index values and for the start or stop field of an index range (as in the example). Dealing with negative indices in an index list would slow the code down too much, so the values in an index list may not be zero or negative.