# Variable in JuMP with arc index

Dear all
I have defined the following variable:

``````@variable(modelo, x[(i,j) ∈ A, t ∈ T] >= 0)
``````

where

``````A = [
(1, 5)
(1, 6)
(1, 7)
(2, 5)
(2, 6)
(2, 7)
(3, 5)
(3, 6)
(3, 7)
(4, 5)
(4, 6)
(4, 7)
]; T=1:12
``````

However, when I run the constraint:

``````@constraint(
modelo,
sum(x[i,j,t] for (i,j) ∈ A for t in T) <= 1000
)
``````

an error is obtained.

``````
``````

You need the indexing to match how you’ve defined the variable. In your case, `x` is two dimension, where the first dimension is the elements in `A`, and the second dimension are the elements in `T`. But `x[i, j, t]` attempts to index `x` as if it had three dimensions. You need `x[(i, j), t]` instead.

``````using JuMP
A = [
(1, 5)
(1, 6)
(1, 7)
(2, 5)
(2, 6)
(2, 7)
(3, 5)
(3, 6)
(3, 7)
(4, 5)
(4, 6)
(4, 7)
];
T = 1:12
model = Model()
@variable(model, x[(i,j) ∈ A, t ∈ T] >= 0)
@constraint(
model,
sum(x[(i,j),t] for (i,j) ∈ A for t in T) <= 1000
)
``````

I’d write this as

``````model = Model()
@variable(model, x[A, T] >= 0)
@constraint(model, sum(x[arc, t] for arc in A for t in T) <= 1000)
``````
2 Likes

I think Oscar’s proposal is the simplest solution in JuMP, but if you are curious on another way of modeling with sparse structures (e.g. graphs), you could also have a look at SparseVariables.jl. This package provides an alternative container for holding variables that is efficient if you are dealing with large scale sparse problems.

``````using JuMP
using SparseVariables

I = 1:4
J = 5:7

A = [
(1, 5)
(1, 6)
(1, 7)
(2, 5)
(2, 6)
(2, 7)
(3, 5)
(3, 6)
(3, 7)
(4, 5)
(4, 6)
(4, 7)
];
T = 1:12

model = Model()
@variable(model, x[start = I, end = J, time = T] >= 0; container = IndexedVarArray)
for (i,j) in A, t in T
insertvar!(x, i, j, t)
end
@constraint(model, sum(x) <= 1000)
``````

This may be more easy to work with if you have constraints that e.g, need to be provided for a specific vertex

``````for i in I
@constraint(model, sum(x[i, :, :]) <= 100)
end
``````