Collection of ranges in Julia

Viewed 263

The task appears simple, but i am struggling to get the way of initializing a vector (array, collection, or similar) of ranges. That is, I need to do something like this:

vec_of_ranges = HOW TO INITIALIZE THIS?
for i=1:10
   range = i:20
   vec_of_ranges[i]=range
end

Can anyone give me a hint on how to do this? I need it so I can then evaluate a given array on that collection of ranges...

Thanks in advance!

2 Answers

If you type typeof(1:50) you get UnitRange{Int64}

So you need an array of UnitRange

Try this:

vec_of_ranges = Array{UnitRange{Int64},1}(undef, 10)
for i=1:10
   range = i:20
   vec_of_ranges[i]=range
end

You might also want to use the fill() command

vec_of_ranges = fill(1:20, 10)

If you would use a comprehension you get both steps (i.e. getting the right element type and filling the contents) for free in one shot:

julia> [i:20 for i in 1:10]
10-element Array{UnitRange{Int64},1}:
 1:20
 2:20
 3:20
 4:20
 5:20
 6:20
 7:20
 8:20
 9:20
 10:20

alternatively you can use map:

julia> map(i -> i:20, 1:10)
10-element Array{UnitRange{Int64},1}:
 1:20
 2:20
 3:20
 4:20
 5:20
 6:20
 7:20
 8:20
 9:20
 10:20

If you wanted to use broadcasting you can do:

julia> UnitRange.(1:10, 20)
10-element Array{UnitRange{Int64},1}:
 1:20
 2:20
 3:20
 4:20
 5:20
 6:20
 7:20
 8:20
 9:20
 10:20
Related