logo

Comprehensions in Julia 📂Julia

Comprehensions in Julia

Code

In Julia, like in Python, comprehension is possible. Comprehension is a method of creating arrays that involves embedding conditional expressions directly into the array.

For instance, if you want to define an array containing integers sequentially from $0$ to $9$, you can embed a for loop directly into the array.

julia> [i for i ∈ 0:9]
10-element Vector{Int64}:
 0
 1
 2
 3
 4
 5
 6
 7
 8
 9

julia> [i*ones(8) for i ∈ 1:9]
9-element Vector{Vector{Float64}}:
 [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
 [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0]
 [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]
 [4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0]
 [5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0]
 [6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0]
 [7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0]
 [8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0]
 [9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0]

julia> stack([i*ones(8) for i ∈ 1:9], dims=2)
8×9 Matrix{Float64}:
 1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0
 1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0
 1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0
 1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0
 1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0
 1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0
 1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0
 1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0

Nested for loops are also possible.

julia> X = 1:4
1:4

julia> Y = [-1, 0, 1]
3-element Vector{Int64}:
 -1
  0
  1

julia> [x*y for x=X, y=Y]
4×3 Matrix{Int64}:
 -1  0  1
 -2  0  2
 -3  0  3
 -4  0  4

Environment

  • OS: Windows11
  • Version: Julia 1.10.0