May 2019
Beginner to intermediate
466 pages
10h 44m
English
Array comprehensions provide a very powerful way to construct arrays. It is similar to the previously discussed array literal notation, but instead of passing in the actual values, we use a computation over an iterable object.
An example will make it clear:
julia> [x += 1 for x = 1:5]
10-element Array{Int64,1}:
2
3
4
5
6
This can be read as—for each element x within the range 1 to 5, compute x+1 and put the resultant value in the array.
Just like with the plain array literals, we can constrain the type:
julia> Float64[x+=1 for x = 1:5]
5-element Array{Float64,1}:
2.0
3.0
4.0
5.0
6.0
Similarly, we can create multi-dimensional arrays:
julia> [x += y for x = 1:5, y = 11:15] 5×5 Array{Int64,2}: 12 13 14 15 16 13 14 15 16 17 14 ...Read now
Unlock full access