User Tools

Site Tools


gams:the_if-else_statement

The IF-ELSE statement

The IF-ELSE statement is useful to branch conditionally around a group of statements. In some cases this can also be written as a set of $ conditioned statements, but the IF statement may be used to make the GAMS code more readable.

Syntax

An optional ELSE part allows you to formulate traditional IF-THEN-ELSE constructs. The syntax is:

   IF (condition,
          statements;
          .
          .
       ELSE
          statements;
          .
          .
      );

Warning: One cannot make declarations or define equations

       inside an IF statement. 

Example 1

For instance,

   P(I)$(F GT 0) = F*P(I) ;
   Q(J)$(F GT 0) = F*Q(J) ;

can also be written as

   IF (F GT 0,
       P(I) = F*P(I) ;
       Q(J) = F*Q(J) ;
      ) ;

Example 2

One can also use IF statements to control the SOLVE statement. For instance, consider the following bit of GAMS code:

   IF ((ml.modelstat eq 4),

* model ml was infeasible * relax bounds on X and solve again

           x.up(j) = 2*x.up(j) ;
           solve ml using lp minimizing lp ;
       ELSE
          IF ((ml.modelstat ne 1),
              abort "Error solving model ml ;
             );
      );

Example 3

The following GAMS code is illegal since one cannot define equations inside an IF statement.

   If (s GT 0,
       eq.. sum(i,x(i)) =g= 2 ;
      );

Example 4

The following GAMS code is illegal since one cannot make declarations inside an IF statement.

   IF (s gt 0,
       scalar y ; y = 5 ;
      );
IMPRESSUM / LEGAL NOTICEPRIVACY POLICY gams/the_if-else_statement.txt · Last modified: 2007/02/02 16:48 (external edit)