Cannot collect variables with index not starting from 1 in a vector



I am trying to create anonymous variables and collect them in a vector. But only those with index starting from 1 can be collected. Others will result in error. Is there any method to push those variables into a vector? I paste an example below. Thanks

using JuMP,Gurobi
x=Vector{Variable}[] # the vector used to collec variables
y1=@variable(m,[i=1:4],basename="y1") # variable with index starting from 1
y2=@variable(m,[i=4:6],basename="y2") # variable with index not starting from 1
y3=@variable(m,[i in I],basename="y3") # variable with index in an array
push!(x,y1) # good
push!(x,y2) # error
push!(x,y3) # error

The error reported is

MethodError: Cannot `convert` an object of type JuMP.JuMPArray{JuMP.Variable,1,Tuple{UnitRange{Int64}}} to an object of type Array{JuMP.Variable,1}
This may have arisen from a call to the constructor Array{JuMP.Variable,1}(...),
since type constructors fall back to convert methods.

 in push!(::Array{Array{JuMP.Variable,1},1}, ::JuMP.JuMPArray{JuMP.Variable,1,Tuple{UnitRange{Int64}}}) at .\array.jl:479


This is because the types of y2 and y3 are not Vector{Variable}, and you are trying to push them to a typed array x where each element must be of type Vector{Variable}.


Yes, I can tell that. But it is weird to me that y2 and y3 are in different type just because the way I define their index.


What @joehuchette means is that your array is declared wrong. It should be Variable[] not Vector{Variable}[]. I strongly suspect the error is actually on the first push.


It’s weird, but we support things like @variable(m,[i=1:N,j=1:N]) which returns a plain matrix, and @variable(m,[i=1:N,j=i:N]) which returns a specialized JuMPDict. If you have suggestions on improvements for the syntax, I’m all ears. The solution to your code snippet is to define x = [].


The x defined as that works for me. Now I understand why they are in different types. Thank you so much.