Increase a range object by some amount

Hello,

I am trying to increase a range object that has already been created. Basically, I have a range 1,2,3,..,8,9,10 and then i want to add 11,12,13 to the same range object so that i will get a final range of 1,2,3,...11,12,13. Is there a way to do this?

julia> r1=1:10
1:10

julia> r2=11:13
11:13

julia> r1+r2
ERROR: DimensionMismatch("argument dimensions must match")
Stacktrace:
  [1] +(::UnitRange{Int64}, ::UnitRange{Int64}) at .\range.jl:1005
 [2] top-level scope at none:0

What am i doing wrong?
Thanks

You could just write a function to do:

julia> @assert last(r1) + 1 == first(r2)

julia> UnitRange(first(r1), last(r2))
1:13

You can also vcat ranges, but note that this collects them into actual arrays, which is wasteful:

julia> vcat(r1, r2)
13-element Array{Int64,1}:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13

1 Like

What if r1=1:5 and r2=11:13 ?

What’s actually being requested here seems to be concatenation of two ranges.

yes concatenation of two ranges

can julia do uneven ranges?

That won’t in general be a range. If you want it to produce another range then you’ll have to write a function that checks that the strides are the same and that the last endpoint of the first range and the first endpoint of the second range are the same. If you don’t care about producing a range then you can just do [r1; r2] which does array concatenation.

4 Likes

Actually, they should probably differ by 1? That seems more in line with arrays concatenation

Right, that’s what I meant.