Create array from range values

I’m trying create a array from ranges in Julia 1.1.

lb = [0,0,0,0,0,0,0];
ub = [4,4,4,2,2,2,6];

range.(lb,ub)
UnitRange{Int64}[7]
0:4
0:4
0:4
0:2
0:2
0:2
0:6

Getting this message when I run test

┌ Warning: `range(start, stop)` (with neither `length` nor `step` given) is deprecated, use `range(start, stop=stop)` instead.
│   caller = _broadcast_getindex_evalf at broadcast.jl:578 [inlined]
└ @ Core .\broadcast.jl:578

But for some reason, I cannot create the array when expressed this way:

range.(lb,stop=ub)
MethodError: no method matching (::Colon)(::Int64, ::Array{Int64,1})

I believe dot notation does not broadcast over keyword arguments.
But for your example, you can do this:

julia> lb = [0,0,0,0,0,0,0];
julia> ub = [4,4,4,2,2,2,6];

julia> range.(lb, ub, step=1)
7-element Array{StepRange{Int64,Int64},1}:
 0:1:4
 0:1:4
 0:1:4
 0:1:2
 0:1:2
 0:1:2
 0:1:6

Good suggestion! However, it creates a StepRange, not a UnitRange. For most applications that’s probably fine, but it has slightly worse performance, and could potentially throw off code specialized for unit ranges. If you know that you always want UnitRanges, you could use that directly:

julia> lb = [0,0,0,0,0,0,0];

julia> ub = [4,4,4,2,2,2,6];

julia> UnitRange.(lb, ub)
7-element Array{UnitRange{Int64},1}:
 0:4
 0:4
 0:4
 0:2
 0:2
 0:2
 0:6

If you want to use the colon notation for more flexibility, you can use zip:

julia> [z[1]:z[2] for z in zip(lb, ub)]
7-element Array{UnitRange{Int64},1}:
 0:4
 0:4
 0:4
 0:2
 0:2
 0:2
 0:6

Some alternative forms below that do the same thing… some people prefer one syntax over the other:

julia> zip(lb, ub) .|> z -> z[1]:z[2]
7-element Array{UnitRange{Int64},1}:
...

julia> map(z -> z[1]:z[2], zip(lb, ub))
7-element Array{UnitRange{Int64},1}:
...

julia> (z -> z[1]:z[2]).(zip(lb, ub))
7-element Array{UnitRange{Int64},1}:
...
5 Likes