logo

Julia's Multidimensional Indices 📂Julia

Julia's Multidimensional Indices

Overview

Julia provides a type of index that can reference multi-dimensional arrays, known as CatesianIndex1. Naturally, the naming Catesian comes from the Cartesian product, which is the product of sets.

Code

julia> M = rand(0:9, 4,4)
4×4 Matrix{Int64}:
 9  3  7  0
 8  6  2  1
 3  8  4  9
 5  6  8  2

For example, let’s assume you want to access the element 9, which is in the 3rd row and 4th column of the matrix M.

julia> pt = (3,4)
(3, 4)

julia> M[pt]
ERROR: LoadError: ArgumentError: invalid index: (3, 4) of type Tuple{Int64, Int64}

julia> M[pt[1],pt[2]]
9

Intuitively, it seems like you could simply use the tuple pt = (3,4), but people familiar with programming will recognize that this method has its flaws. Typically, when referencing a two-dimensional array, especially a matrix, you need to explicitly separate the two integers like pt[1],pt[2].

julia> pt = CartesianIndex(3,4)
CartesianIndex(3, 4)

julia> M[pt]
9

Thankfully, Julia provides the CatesianIndex, which allows you to pass the index as a whole. By converting the tuple directly into a CatesianIndex, you get the desired result.

Full Code

M = rand(0:9, 4,4)

pt = (3,4)
M[pt]
M[pt[1],pt[2]]

pt = CartesianIndex(3,4)
M[pt]

Environment

  • OS: Windows
  • julia: v1.7.0