Loops

<< Click to Display Table of Contents >>

Navigation:  Gekko User Guide > Data Management User Guide > Gekko programs >

Loops

Previous pageReturn to chapter overviewNext page

Note: If you are running one of the examples interactively in the Gekko input window, you should mark the code from for to the corresponding end, followed by [Enter]. Executing a FOR loop line by line in the Gekko input window will not work.

clip0088

 

Also, beware that you may often use implicit looping over lists, as shown in the next section.

 

Loops are used when the same statements or calculations reused over several variables. Loops can simplify and reduce the length of program files considerably. In Gekko, the FOR statement is used for looping, and lists are often used in combination with loops.

 

Example with lists:

 

kax = 1; kay = 2; kbx = 3; kby = 4;
#= a, b;
#= x, y;
for string %= #i;
  for string %= #j;
    prt k{%i}{%j};
  end;
end;

 

This will print the timeseries kax, kay, kbx, kby, one by one. In this particular case, the user could just use prt x{#i}{#j};, and Gekko would auto-unfold and print the same timeseries (cf. the section on array-series), but for many other purposes, fine-grained looping can be practical. You may also obtain roughly the same output with prt {'k*'};, but the difference is that the wildcard version includes all variables starting with 'k', possibly including irrelevant variables.

 

When using a FOR loop, the type of the loop variable must always be stated (the same is the case for function and procedure definitions), and a FOR loop must always end with a matching END statement.

 

FOR loops can also be used for date and value variables. Regarding these types, intervals are often used (and the by keyword can be used for step length), for instance:

 

%v1 = 1;
%v2 = 99;
%sum = 0;
for val %= %v1 to %v2 by 2;
  %sum += %v;
end;
//%sum = 2500 (sum of uneven numbers)
 
// -----------------------------------------
option freq q;
time 2020q1 2021q4;
= 1, 2, 3, 4, 5, 6, 7, 8;
= 100;
%d1 = 2020q1;
%d2 = 2021q4;
for date %= %d1 to %d2 by 2;
  y[%d] = x[%d];
end;
prt y;
// y = 100, 2, 100, 4, 100, 6, 100, 8;
// every second quarter skipped

 

Lists may also contain values or dates, and such lists may be looped in the same way as the first example (looping over a list of strings). Synchronized/parallel loops are possible, too, for instance:

 

#= a, b;
#= x, y;
for string %= #i  string %= #j;
  tell 'Combination {%i}, {%j}';
end;
//------------------------------------------
//output:
//
// Combination a, x
// Combination b, y

 

The sum() function over lists is practical for repetitive sums like p1*fx1 + p1*fx2 + p3*fx3 and similar. Such sums are often used for array-series, too.