Programming

Flow Control

Logical variables have another important use: flow control.
Flow control allows different code to be executed depending on whether certain conditions are met.
Two flow control structures are available:

  1. if . . . elseif . . . else
  2. switch . . . case . . . otherwise

If Elseif Else

The generic formof an if . . . elseif . . . else block

if logical1
Code to run if logical1 true
elseif logical2
Code to run if logical2 true and logical1 false
elseif logical3
Code to run if logical3 true and logicalj false, j < 3
. . .
. . .
else
Code to run all logical’s false
end

Obiously you can build more simpler just with one condition.
An example.

if isunix == 1 &amp;&amp; ismac == 0
    disp('You are running MATLAB on Linux.');
elseif ismac == 1
    disp('You are running MATLAB on a MAC.');
elseif ispc == 1
    disp('You are running MATLAB on a PC.');
else 
    disp('Unknown OS.');
end

Switch Case Otherwise

The basic structure of this block is to find some variable whose value can be used
to choose a piece of code to execute (the switch variable).

switch variable
case value1
Code to run if variable=value1 true
case value2
Code to run if variable=value2 true
case value3
Code to run if variable=value3 true
. . .
. . .
otherwise
Code to run if variable 6= value j
end

Switch Case Otherwise is very useful as choice when user is running a program.
For example, suppose that you want to estimate GARCH processes with different options (GARCH type model, mean equation, distribution of innovations etc).

   % Starting Values
    switch garchtype
        case 1 % GARCH
            startingvalues = [a0; a1; a2; a3; b0; b1; b2; by];
        case 2 % GJR
            startingvalues = [a0; a1; a2; a3; b0; b1; b2; by; 0.15*ones(p,1)/p];
.....
.....
         case 8 % NAGARCH
            startingvalues = [a0; a1; a2; a3; b0; b1; b2; by; 0.15*ones(p,1)/p]; 
    end
    switch errortype
        case 1 % GAUSSIAN
            k=0;
.....
....
        case 6 % Gram-Charlier sk = 0.1, and nu = 4
            startingvalues = [startingvalues; 0.1; 4];
            k=2;
    end  
end 

% Specify constraints used by fmincon (A, b) and lower and upper bounds of parameters
% Example: GARCH(1,1): b0&gt;0, b1&gt;0, b2&gt;0, and b1 + b2 &lt;1
switch garchtype
    case 1 % GARCH
        A = [zeros(1+p+q,1+z) -eye(1+p+q) zeros(1+p+q,k+v); zeros(1,2+z) ones(1,p+q) zeros(1,k+v)];
        b = [zeros(1,1+p+q) [1 - 1e-6]];
        lowerbounds  = [-1; -ones(ar+ma,1); lx; 1e-8*ones(p+q+1,1); ly];
        upperbounds  = [ 1; ones(ar+ma,1); ux; ones(p+q+1,1); uy];
    case 2 % GJR
        A = [zeros(1+p+q,1+z) -eye(1+p+q) zeros(1+p+q,p+k+v); zeros(1,2+z) ones(1,p+q) 0.5*ones(1,p) zeros(1,k+v)];
        b = [zeros(1+p+q,1); [1 - 1e-6]]; 
        lowerbounds  = [-1;  -ones(ar+ma,1); lx; 1e-8*ones(p+q+1,1); ly; -1*ones(p,1)];
        upperbounds  = [ 1;  ones(ar+ma,1); ux; ones(p+q+1,1); uy; 1*ones(p,1)];
    case 3 % EGARCH
.....
.....
     case 8 % NAGARCH
        % -1 &lt; asym &lt; +1
        A = [zeros(1+p+q,1+z) -eye(1+p+q) zeros(1+p+q,p+k+v); zeros(1,2+z) ones(1,p+q) zeros(1,p+k+v)];
        b = [zeros(1,1+p+q) [1 - 1e-6]];
        lowerbounds  = [-1;  -ones(ar+ma,1); lx; 1e-8*ones(p+q+1,1); ly; -1*ones(p,1)];
        upperbounds  = [ 1;  ones(ar+ma,1); ux; ones(p+q+1,1); uy; 1*ones(p,1)]; 
end
if garchtype ~= 3
switch errortype
    case 1 % GAUSSIAN Distribution
    case 2 % STUDENT'S t-Distribution
        % DoF must be larger than 2 in order for the Student's t-distribution 
        % to be well defined
        lowerbounds = [lowerbounds; 2+1e-6]; 
        upperbounds = [upperbounds; 100+1e-6];
    case 3 % GED Distribution
.....
.....
    case 6 % Gram-Charlier Expansion 
        % 3 &lt; kurtosis &lt; +oo
        lowerbounds = [lowerbounds; -10+1e-6; -inf];
        upperbounds = [upperbounds; 10+1e-6; inf];    
end
end

Loops

Loops are the most useful programming structure (not only) in MATLAB.
MATLAB has two loop blocks,

  1. for, it loops over a predetermined iterator,
  2. while, it loops as long as some logical expression is satisfied.

All for loops can be expressed as while loops although the opposite is not true; gf we use break statement they are nearly equivalent, although it is generally preferable to use a while loop to a for loop and a break statement.

for

for iterator=vector
Code to run
end

iterator is a variable name where the loop is iterating over whire vector is a vector of data.

count=0;
for i=1:100
count=count+i;
end

Or another one,

count=0;
x=[1 3 4 -9 -2 7 13 -1 0];
for i=x
count=count+i;
end

Here you have an example of nested for loop, we create a square matrix with lower triangle equal to 1, diag 0 and upper triangle equal 2.

matrix=zeros(10,10);
    for i=1:size(matrix,1)
        for j=1:size(matrix,2)
            if i&gt;j
                matrix(i,j) = 1;
            elseif i&lt;j
                matrix(i,j) = 2;
            else
                matrix(i,j) = 0;
            end
        end
     end

while

It is useful when the number of iterations needed is unknown, when a loop should only stop if a certain condition is met.
Two condition are essential when you are using loop while:

  • logical should be true when the loop begins (or the lop will be ignored),
  • the inputs to the logical variable must be updated inside the loop. If they are not, the loop will continue for ever (hit CTRL+C to break an errant loop).

while logical
Code to run
Update to logical inputs
end

We can rewrite the counter example in while loop made in the for loop,

count=0;
i=1;
    while i&lt;=10
          count=count+i;
          i=i+1; 
    end

while loops should generally be avoided when for loops will do. However, there are situations where no for loop equivalent exists.

mu=1;
index=1;
while abs(mu)&gt;.0001
   mu=(mu+randn)/index;
   index=index+1;
end
In the example above, we don't know in advance the number of iterations required is not known in advance and since randn is a standard normal pseudo-random number, it may take many iterations until this criteria is met.
Any finite for loop cannot be guaranteed to meet the criteria.

break

break can be used to break out of a loop. For example we can make for loops behave similar to a while loop.

for iterator=vector
   Code to run
   if logical
     break
   end
end

The difference is that while loop could potentially run for more iterations.
We can use break in while loop to create an exit condition when otherwise if left alone, it will run indefinitely.

while 1
  x = randn;
end

Let’s insert an exit condition,

while 1
  x = randn;
  if x<0
    break
  end
end

continue

continue makes advance the loop to the next iteration and skipping any remaining code in the body of the loop.
It use can always be avoided using if. . .else blocks, but it can make code tidier.

for i=1:10
    if (i/2)==floor(i/2)
       continue
        end
    i
end

continue is forcing the loop to the next iteration (i) when the logical test is true.

Exercises


%d bloggers like this: