Search code examples
variablesjuliasparse-matrixmathematical-optimizationjulia-jump

How to add a new variable to an already existing set of variables (based on a SparseAxisArray) in JuMP?


I am currently working with a JuMP model where I define the following example variables:

using JuMP
N = 3
outN = [[4,5],[1,3],[5,7]]

m = Model()
@variable(m, x[i=1:N,j in outN[i]] >=0)

At some point, I want to add, for example, a variable x[1,7]. How can I do that in an effective way? Likewise, how can I remove it afterwards? Is there an alternative to just fixing it to 0?

Thanks in advance


Solution

  • You're probably better off just using a dictionary:

    using JuMP
    N = 3
    outN = [[4,5],[1,3],[5,7]]
    
    model = Model()
    x = Dict(
        (i, j) => @variable(model, lower_bound = 0, base_name = "x[$i, $j]")
        for i in 1:N for j in outN[i]
    )
    x[1, 7] = @variable(model, lower_bound = 0)
    delete(model, x[1, 4])
    delete!(x, (1, 4))
    

    Nothing about JuMP restricts you to using only the built-in variable containers: https://jump.dev/JuMP.jl/stable/variables/#User-defined-containers-1