Multi-dimensional arrays

A multi-dimensional array (or N-dimensional array, including one that is zero-dimensional) is a contiguous block of memory that is divided into elements that are indexed by the corresponding number of indices (N).

The indices of the array are specified by a sequence of N ranges of pairs of integers m1..n1, ..., mN..nN where $m_k \leq n_k$ for each $k$, and the size of the array is the product of $m_k - n_k + 1$. Like one-dimensional arrays, the default value of the elements of the array is 0:

[> B1 := Array( 7..16, -5..-2, -1..7 ):

This array has $10 \times 4 \times 9 = 360$ entries. Again, refrain from ever printing arrays, as this will be a very expensive operation in both time and space.

You can assign to any sequence of indicies where each sequence is in the correct range, so these are all valid:

[> B1[7, -5, 7] := x:
[> B1[16, -2, -1] := x^2:

while these are all invalid:

[> B1[8, 5, 4] := x:
Error, Array index out of range
[> B1[4, -3, 5] := x^2:
Error, Array index out of range
[> B1[16, -2, -2] := x^3:
Error, Array index out of range

Initializing arrays

Once you have specified the range of indices, you can specify the initial values in one of the following three ways:

  1. A $N$ times nested list of expresssions which can have more or less elements than the array will have. If there are insufficient entries in the list of lists, the balance of elements are assigned 0.
  2. A function mapping $N$ indices onto a value. Each entry of the array will be given a value using this technique.
  3. A set of equations of the form (i1, i2, ..., iN) = value where the indices are integers between the corresponding lower and upper bounds of the array, and the value is what will be assigned to that index. If an entry is not initialized, it is initialized to zero.

For example:

[> B3 := Array( 1..2, 1..2, [[1, 2], [3, 4]] ):
[> B4 := Array( -5..2, 5..12, 4..2, (n1, n2, n3) -> n1*n2*n3 ):
[> B3 := Array( -5..5, -5..5, -5..5, {(1,1,1) = x^2, (5, -5, 3) = x^3} ):

In each of these, you can access or assign to the entries in a constant run time. This is much more efficient than a list of list, where changing an entry in a list requires the generation of a completely new list of lists, so the run time is very large.

There are other features of such arrays that are not documented here, which you can read about in the help pages.