logo

Slicing and Indexing of Arrays in Julia 📂Julia

Slicing and Indexing of Arrays in Julia

Overview

Julia is a language that mixes the advantages of R, Python, and Matlab. Arrays are fundamental to programming, and their usage reveals traces of these languages.

Code

Matrix

julia> M = [1. 2. ; 3. 4.]
2×2 Array{Float64,2}:
 1.0  2.0
 3.0  4.0

julia> size(M)
(2, 2)

julia> length(M)
4

For matrices, the syntax is defined and used almost exactly like Matlab. The size() function is used just like in Matlab, and serves the same purpose as the .shape property in Python’s numpy package. length(), unlike in Matlab, returns the total number of elements.

2D Arrays

julia> x = [[1,2,3,4] for _ in 1:4]; x
4-element Array{Array{Int64,1},1}:
 [1, 2, 3, 4]
 [1, 2, 3, 4]
 [1, 2, 3, 4]
 [1, 2, 3, 4]

Placing loops inside arrays is a usage commonly seen in Python. This allows for a similar replication of the rep() function from R.

Slicing

julia> y = [3,2,5,1,4]
5-element Array{Int64,1}:
 3
 2
 5
 1
 4

julia> y[[4,2,1,5,3]]
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> y[3:end]
3-element Array{Int64,1}:
 5
 1
 4

julia> y[3:4] .= -1; y
5-element Array{Int64,1}:
  3
  2
 -1
 -1
  4

Indexing is similar to R, where providing an array of indexes will print the elements in that order. Seeing that the last index of an array is represented as end suggests that slicing is influenced by Matlab. Finally, using .= to directly assign -1 to the 3rd and 4th elements is also reminiscent of Matlab.

Indexing

julia> x = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> x[1,:]
2-element Array{Int64,1}:
 1
 2

julia> x[[1],:]
1×2 Array{Int64,2}:
 1  2

julia> x[1,1] = -1; x
2×2 Array{Int64,2}:
 -1  2
  3  4

What is peculiar is that the result of indexing can vary depending on how it is performed. Conceptually, inserting the same thing should yield the same result; however, if elements are entered, the result is in elements, and if an array is entered, the result is in array form. This makes Julia hard to use while also providing significant help in implementing sophisticated features.

Environment

  • OS: Windows
  • julia: v1.5.0