Assigning JuMP VariableRef to an array position

Hi,

Is it possible to assign a decision variable to an array position?
For example:

using JuMP
m = Model()

@variable(m, x)

arr = zeros(100)
arr[1] = x

x is a decision variable which will be decided by the model when it is run, is it possible to assign it to an array position?

Thanks!

Yes, it is possible but the array type should be JuMP.VariableRef. Here zeros(100) creates an array of Float64 and JuMP.VariableRef is not convertible to Float64.
You can try

using JuMP
model = Model()
@variable(model, x)
arr = Vector{JuMP.VariableRef}(undef, 100)
arr[1] = x

Oh okay, but I have a small issue now.

@variable(m, delta0)

amort = delta0/T

bal = Vector{JuMP.VariableRef}(undef, 100)

bal[1] = delta0
for i = 2:100
	bal[i] = bal[i-1] - amort
end

I can now assign a decision variable to the first array position bal[1], but for the following positions from [2] onwards, I need to deduct a certain value amort. But I get an error MethodError: Cannot convert an object of type GenericAffExpr{Float64,VariableRef} to an object of type VariableRef
So I asked about this in a previous post and someone advised to use regular zeros array, and that allowed me to subtract amort from bal[1]. So I have this dilemma, where I need a JuMP array for decision variable storage, but also need the properties of a zeros array, and am not sure what to do.
If someone can please help, it would be greatly appreciated. This is the link to my other related question: https://discourse.julialang.org/t/for-loop-error/26210/7

Thanks!

Specify your model equality relationships as constraints. Also, use the array-form of the @variable and @constraint macros for efficiency. See http://www.juliaopt.org/JuMP.jl/v0.19.2/variables/#Variable-containers-1.

@variable(m, delta0)

amort = delta0/T

@variable(m, bal[i=1:100])
@constraint(m, bal[1] == delta0)
@constraint(m, [i=2:100], bal[i] == bal[i-1] - amort)
1 Like

Try bal = Vector{JuMP.AffExpr}(undef, 100)

1 Like

Thank you @blegat and @ianfiske, both your suggestions worked!