# Array

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

## Array(I1, I2,.., In, a)

Creates an array with indexes «I1»...«In», and uses «a» for the values within the array.

When «a» is an atom (scalar), then an array is created having the same value, «a», in every cell. For example, Array(I, 1) is an array indexed by I with the value 1 in every cell.

When creating an array on one index, you can specify the initial values using a list, e.g.,

Array(I, [2, 3, 5, 7, 11])

If the length of the list does not match the length of your index, an warning is issued. If you ignore the warning, or if you surround the expression in IgnoreWarnings(), only the first Size(I) values of the list are used, and extra cells are null-padded.

You can specify the initial data for a 2-D array by nesting lists, e.g.,

Array(I, J, [[2, 3, 5], [7, 11, 13], [17, 19, 23], [29, 31, 37]])

When nested in this fashion, the first index listed (e.g., I) corresponds to the outermost list, while the last index (e.g., J) corresponds to the innermost list.

You can also supply an array for «a», or an expression that computes an array. For example, when you supply one index, the expression should evaluate to a 1-D array. This has the effect of re-indexing the array, changing from the original index used by the array to the new index. However, re-indexing an array in this fashion is a bad practice and is highly discouraged. When you want to re-index, it is better to use a[@I = @J] (see Subscript-Slice Operator). The latter will work even if new dimensions are introduced into a later (through array abstraction), while Array(J, a) could very well break since the outer-dimension of a could change unexpectedly.

## Indexes that change

When an index passed to Array changes, the expression is not re-written or adjusted. If you want to ensure that the values retain their positions relative to the index elements, you should use a Table instead, so that Table Splicing maintains this correspondence. This is a key difference between the Table function and the Array function. However, Table can only appear at the top-level of a definition, not within a sub-expression, whereas Array can appear anywhere.

Since Array does not adjust, it is best used only with indexes whose elements are not likely to change.

## Examples

Index I := 1..5
Index J := 1..5
Array(J, 1) →
J ▶
1 2 3 4 5
1 1 1 1 1
Array( J, ["apple", "banana", "cherry", "date", "eggplant"]) →
J ▶
1 2 3 4 5
"apple" "banana" "cherry" "date" "eggplant"
Array(I, J, [[6, 2, 6, 3, 1], [2, 4, 3, 1, 3], [6, 3, 9, 3, 4], [3, 1, 3, 8, 4], [1, 3, 4 ,4, 7]]) →
J
I 1 2 3 4 5
1 6 2 6 3 1
2 2 4 3 1 3
3 6 3 9 3 4
4 3 1 3 8 4
5 1 3 4 4 7