Multi-dimensional arrays

Intermediate Julia

Anthony Markham

Quantitative Developer

1D array recap

  • A vector is simply an array with only one dimension.
# Create a 1-D array (vector)
my_1d_array = [1, 2, 3, 4, 5, 6]
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6
Intermediate Julia

2D array structure

  • A 2D array is also referred to as a matrix.
  • A tabular representation of data, with multiple rows and columns.
  • Remove the commas between elements, use the semicolon ; to denote a new row.
# Define a matrix
my_matrix = [1 2 3; 4 5 6]
2×3 Matrix{Int64}:
 1  2  3
 4  5  6
Intermediate Julia

Indexing a 2D array

  • Indexing is similar to vectors, but we need two indexes, not one.
  • The first index is the row, and the second is the column.
2×3 Matrix{Int64}:
 1  2  3
 4  5  6
# Return '2' - first row, second column
println(my_matrix[1, 2])
2
Intermediate Julia

Slicing a 2D array

  • The colon : operator allows us to select all values in a row or column.
  • This is the same as the previous DataFrame slicing that we have seen!
2×3 Matrix{Int64}:
 1  2  3
 4  5  6
# Return the entire third column
println(my_matrix[:, 3])
[3, 6]
Intermediate Julia

getindex()

  • getindex() is another way to access elements within an array.
  • Pass the variable name and the two indices to return the value at these indices.
2×3 Matrix{Int64}:
 1  2  3
 4  5  6
println(getindex(stock, 1, 2))
2
Intermediate Julia

2D array concatenation

  • Array concatenation involves combining two arrays together by stacking them.
array_1 = [1 2 3; 4 5 6]
array_2 = [7 8 9; 10 11 12]
concat_array = [array_1; array_2]
4×3 Matrix{Int64}:
  1   2   3
  4   5   6
  7   8   9
 10  11  12
Intermediate Julia

Let's practice!

Intermediate Julia

Preparing Video For Download...