Loop

Top  Previous  Next

The Loop statement allows one to execute a group of statements for each element of a set.  The syntax of the Loop statement is,

 

Loop((sets_to_vary),

 statement or statements to execute

);

 

If the sets_to_vary contains one set, then the statement can be

 

Loop(set_to_vary,

 statement or statements to execute

);

 

The Loop statement causes GAMS to execute the statement or statements for each member of sets_to_vary in turn.  The order of evaluation is determined by the contents of the UEL list as discussed in the Rules for Item Capitalization and Ordering chapter.

Example:

The following syntax would cause the model to be solved for each element within the set I.  In that Loop I first revise some data in the model in accordance with the ith element of savparam.  In turn the objective value would be saved in the ith element of data.

 

Loop (i,

  problemdata=savparam(i);

  Solve mymodel using lp maximizing profit;

  Data(i)=profit.l;

) ;

Notes:

Within the Loop the index is treated as If it referenced only the single set element that the Loop index takes on during each pass.  Thus If the set I in the example above had the elements corn and wheat the first pass would act as If it were

 problemdata=savparam("corn");

 Solve mymodel using lp maximizing profit;

 Data("corn")=profit.l;

 

 and on the second pass as If it were

 problemdata=savparam("wheat");

 Solve mymodel using lp maximizing profit;

 Data("wheat")=profit.l;

 

The Loop set elements addressed may be subject to a conditional as discussed in the Conditionals chapter.
Loops may involve more than one set e.g. Loop((I,j), statement or statements to execute);
One cannot include parameter, acronym, set, file, table, model, equation, variable or scalar statements or .. equation declarations inside a Loop statement.
It is illegal to modify any set indexed by the Loop statement inside the body of the Loop.
Solves can appear within a Loop and Loops are often conveniently used to do a scenario based study with repeated solves.
A Loop is often used to perform iterative calculations.