|
<< Click to Display Table of Contents >> Conditional statements |
![]() ![]()
|
Note: If you are running one of the examples interactively in the Gekko input window, you should mark the code from if to the corresponding end, followed by [Enter]. Executing an IF statement line by line in the Gekko input window will not work. |
The IF statement is used to execute statements if a certain condition is met (and an optional ELSE statement will execute other statements if not). The syntax is pretty standard for programming languages, for instance:
%x1 = 2; %x2 = 3; |
If the condition is true, the following statements are executed, and if the condition is false, ELSE can be used to execute alternate statements. You normally compare scalar expressions via one of the following comparison operators: <, <=, ==, >=, > or <>, and these operators can also be combined with the logical keywords and, or, and not.
You may also compare two whole timeseries, but beware that there are some special rules in play in that case, and there are also special rules when one or both of the values contain missing values (more here or here).
Several terms can be combined with and, or, and not, like in the following example:
if (not(x[%t] > 100 or %x == 'yes') and (%x1 > %x2)); |
Below is an example of a part of a program where the program file interrupts, if the variable fvar has a zero value in the period %t.
if (fvar[%t] == 0); |
You can also combine ACCEPT and IF to control the flow of a program interactively:
accept string %yesno 'Do you want to multiply x by 1000?'; |
When comparing, you may need to convert between variable types. In the following example, %s is a text string, %d is a date, and %v is a value.
%s = '2012'; |
When comparing those, you will need to convert %s and %d to values, for instance:
if (val(%s) == val(%d) and val(%s) == %v and val(%d) == %v); |
It should be mentioned that Gekko supports $-conditionals, similar to how these work in GAMS. These are a kind of inline if-conditions, an example:
time 2010 2013; |
In the last statement, Gekko checks the condition for each period, and if it is true, x2 is used, otherwise the value is 0. Also see the iif() function with similar capabilities.