Engee documentation
Notebook

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:

In [ ]:
A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
Out[0]:
4×4 Matrix{Int64}:
  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:

In [ ]:
A[2, 2]
Out[0]:
6

Less common, but sometimes useful, is to use a single index that goes down each column in order:

In [ ]:
println(A[1], " ", A[2], " ", A[3], " ", A[4], " ", A[5])
1 5 9 13 2

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:

In [ ]:
A[1:3, 2]
Out[0]:
3-element Vector{Int64}:
  2
  6
 10

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:

In [ ]:
A[3, :]
Out[0]:
4-element Vector{Int64}:
  9
 10
 11
 12

The colon operator also allows you to create a vector of values with equal intervals, using the more general form start:step:end:

In [ ]:
B = collect(0:10:100)
Out[0]:
11-element Vector{Int64}:
   0
  10
  20
  30
  40
  50
  60
  70
  80
  90
 100

If you omit the step, as in start:end, Julia will use the default step value of 1:

In [ ]:
B = collect(0:100)
Out[0]:
101-element Vector{Int64}:
   0
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
   ⋮
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100