Array indexing¶
Indexing in programming languages is a mechanism for accessing an element of a data array by reference to the array and by one or more expressions whose values determine the position of a component of the array. An index is a set element number that points to a particular array element. This example will demonstrate methods of working with indices.
Let's create a matrix of dimension 4 by 4, the indexes of which will be accessed:
A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
There are two ways to refer to a particular element in an array. The most common way is to specify row and column indices:
A[2, 2]
Less common, but sometimes useful, is to use a single index that goes down each column in order:
println(A[1], " ", A[2], " ", A[3], " ", A[4], " ", A[5])
Using a single index, to refer to a specific element in an array, is called linear indexing.
To refer to multiple elements in an array, use the colon operator, which allows you to specify a range of the form start:end. For example, list the elements in the first three rows and the second column of an array:
A[1:3, 2]
A colon, without a start or end value, specifies all elements in that dimension. For example, display all the columns in the third row of the table:
A[3, :]
The colon operator also allows you to create a vector of values with equal intervals, using the more general form start:step:end:
B = collect(0:10:100)
If you omit the step, as in start:end, Julia will use the default step value of 1:
B = collect(0:100)