Getting the First and Last Elements of an Array

Arrays in Julia are 1-based indexed by default, which means that, usually, we can obtain the first element of the array using the number 1 as an index. However, there are ways in Julia to override this default behavior and use Arrays which start from other indices, including 0 or even negatative indices. As a consequence, it is preferable to use the begin keyword to access the first element in an array. The last element of the array, on the other hand, can be accessed with the end keyword.

A = rand(6)

Array slicing

Array slicing is a very useful operation, which consists in extracting a subset of elements from an array and packaging them as another array. In Julia, we can resort to a very straightforward syntax for this operation.

For example, the code below will extract the odd indices in both dimensions from a 6x6 matrix, and store the results in a new 3x3 matrix.

A = rand(6,6)                   # 6×6 Matrix{Float64}
B = A[begin:2:end,begin:2:end]  # 3×3 Matrix{Float64}
C = A[1:2:5,1:2:5]              # Same as B

Logical Indexing

A very useful way of selecting array elements is to resort to a boolean array, in a process which is often referred to as logical indexing. This can be easily done in Julia by resorting to broadcasting the logical operations of interest.

For example, let’s generate a matrix of random numbers and set to zero all numbers in the array which are below 0.5:

A = rand(6,6)
A[ A .< 0.5 ] .= 0

An array of booleans is created with A .< 0.5, which is subsquently used to access those elements of A. Finally, the assignment = operator is used to set the selected elements to 0. Note that both the comparison and the assignment operator have to be broadcasted.

Iterating over an Array

A = rand(6)
for i ∈ eachindex(A)
    println(string("i=$(i) A[i]=$(A[i])"))

For multidimensional arrays, iterating in a Matlab fashion works for 1-based indexes:

A = rand(6,6)
for i ∈ 1:size(A,1), j ∈ 1:size(A,2)
    println(string("i=$(i) j=$(j) A[i,j]=$(A[i,j])"))

However, it is important to remember that not all arrays in Julia will be 1-based (to see why, see, for example, a blog post by Tim Holly), so this code might lead to errors in the future.

A way to iterate over multidimensional arrays in Julia which is generic (i.e. will work for arrays which are 1-indexed or otherwise) can be performed by using the axes function, which returns the indices of each dimension of an array:

A = rand(6,6)
for i ∈ axes(A,1), j ∈ axes(A,2)
    println(string("i=$(i) j=$(j) A[i,j]=$(A[i,j])"))

Other useful generic-array functions include:

  • firstindex(A,dim)
  • lastindex(A,dim)
  • similar(Array{Float64}, axes(A)) to allocate an array with the same indices as A.

For more details, see the docs.