Declare many variables at once.
Chapter: III — Sets and sums · lesson id indexed-vars · practice lesson
Writing var x1, var x2, …, var x100 doesn't scale. Declare a set I and a family of variables indexed over it with var x, forall i in I. Each x_i is a separate decision variable.
Inline bounds carry over — var 0 <= x <= 1, forall i in I declares one bounded variable per element of I. Parameters work the same way: const v = {1, 3, 5, 2, 4}, forall i in I attaches a value to each element. The objective body uses v_{i} and x_{i} together via sum_{i in I}{ … }.
With no other constraints, the solver picks the upper bound for every x_i.
With no constraints beyond 0 <= x_i <= 1, what does each x_i end up at?
model picks
set I = {1, 2, 3, 4, 5}
const v = {1, 3, 5, 2, 4}, forall i in I
var 0 <= x <= 1, forall i in I
max sum_{i in I}{v_{i} * x_{i}}
end
import elytica
def main():
elytica.init_model("picks")
elytica.run_model("picks")
for i in [1,2,3,4,5]:
print("x"+str(i), "=", elytica.get_variable_value("picks", "x"+str(i)))
print("obj =", elytica.get_best_primal_bound("picks"))
return 0
No code changes needed. Read the model and run it.
no-error — Model solvesnumeric-match — All five x_i hit the upper bound (obj = 1+3+5+2+4 = 15)code-contains — Reads the objective from the solver (no hardcoding)Six items now, different values. Still no constraints, so the result follows the same pattern.
model picks_v
set I = {1, 2, 3, 4, 5, 6}
const v = {2, 6, 1, 4, 3, 5}, forall i in I
var 0 <= x <= 1, forall i in I
max sum_{i in I}{v_{i} * x_{i}}
end
import elytica
def main():
elytica.init_model("picks_v")
elytica.run_model("picks_v")
for i in [1,2,3,4,5,6]:
print("x"+str(i), "=", elytica.get_variable_value("picks_v", "x"+str(i)))
print("obj =", elytica.get_best_primal_bound("picks_v"))
return 0
Read this through MCP: read with path: "lessons/indexed-vars", or resource hlpl://lessons/indexed-vars.