Control Statements

There are four statements available in Matlab which may be used to control the flow of your commands:

for loops

A for loop iterates a body of commands fixed number of times, each time assigning an identifier a different value.

The form of a for loop is:

>> for i=v
  % commands....
end

where v is a row vector. On each iteration of the loop, i will be assigned the elements of v in order. If v is a matrix, on each iteration i will be assigned the columns of v in order.

>> s = 0;
>> for i=[1 2 5 7]
  s = s + i;
end
>> s

s =

    15

>> s = 0;
>> for i=[1 2; 5 7]
  s = s + i;
end
>> s

s =

     3
    12

The standard C for( i = 0; i <= 10; i++ ) may be implemented as:

>> for i=0:10
  % commands....
end

In order to step by a value other than 1, use the trivariate colon operator:

>> for i=start:step:finish
   % commands....
end

A for loop which goes from n to infinity must be implemented using a while loop.

In general, do not use for loops if you can use Matlab's internal vector functions. For example, if you want a vector with sin(x)+1 with x going from 0 to 360 degrees in increments of 0.01 degrees, this is not the way to do it:

>> for i=0:36000                         % about 1 minute
  w(i + 1) = sin(i*pi/180 / 100) + 1;
end
>> v = sin((0:36000)*pi/180 / 100) + 1;  % instantaneous

Example using 10 iterations of Newton's method:

>> s = rand(1);
>> for i=1:10
  s = s + cos(s)/sin(s);
end
>> s                 % your answer may vary

s =

    4.7124

while loops

A while loop iterates a body of commands as long as a condition holds true.

The form of a while loop is:

>> while b
  % commands....
end

where b is a boolean statement. The commands in the body are executed until the boolean expression evaluates to false (0).

An infinite loop may be constructed by using the boolean statement 1, which is always true. You need to use a break statement to terminate such a loop. For example:

while 1
  % commands....
  break;
end

To construct a loop which goes from 1 to infinity, you must maintain your own dummy variable:

i = 1;
while 1
  % commands....
  i = i + 1;
end

You can construct a do-until loop by:

>> flag = 1;
>> while flag
  % commands....
  flag = b;
end

where again, b is your boolean statement. A do-until loop executes at least once, whereas a while loop may never execute the statement commands.

Example using Newton's method:

>> s = rand(1);
>> while abs(cos(s)) > 1e-5
  s = s + cos(s)/sin(s);
end
>> s                          % your answer may vary

s =

    7.8540

if-else-end

An if-else-end statement executes at most one of a number of bodies of commands depending on which condition evaluates to true first, possibly evaluating a default body of commands if none of the conditions are met.

The general if statement is:

>> if b0           % if clause
  % commands....
elseif b1          % 1st elseif clause
  % commands....
elseif b2          % 2nd elseif clause
  % commands....
 .
 .
 .
else               % else clause
  % commands....
end

where b0, b1, b2, ..., are boolean statements. If at any time one of the boolean statements evaluates to true (non-zero), the associated body of commands is executed. If no boolean statements evaluate to true, the commands in the else clause are executed.

Only the first statement if b0 and the end are required. If no else is provided, nothing happens if all of the boolean statements fail. If no elseif clauses are provided, only the first test is performed.

Example of an if statement:

>> s = rand(2,2);
>> dets = det(s);
>> if dets < -1
  s = -s/2;
elseif dets < 0
  s = -s/sqrt(2);
elseif dets < 1
  s = s/sqrt(2);
else
  s = s/2;
end
>> s                       % your answer may vary

s =

    0.2901    0.0409
    0.6319    0.2495

switch

A switch statement executes at most one of a number of bodies of commands depending upon an object matching one of a set of objects.

The general form of a switch statement is:

switch obj
  case set1                % 1st clause
    % 1st commands....
  case set2                % 2nd clause
    % 2nd commands....
   .
   .
   .
  otherwise                % otherwise clause
    % other commands....
end

where obj is either a scalar (1x1 matrix) or a string. set1, set2 may be either scalars or strings, or a collection of scalars or strings enclosed in braces, e.g., {3, 4}. If no match is made, the commands in the otherwise body are executed. The otherwise clauses, as all other clauses, are optional.

The following two are equivalent:

switch x
  case 1
    % commands 1....
  case {2,3}
    % commands 2 3....
  otherwise
    % other commands....
end

if x == 1 then
  % commands 1....
elseif any( x == [2, 3] ) then
  % commands 2 3....
else
  % other commands....
end

Note, unlike C, the switch statement does not fall through. That is, at most one body of commands is executed.

When working with Matlab interactively, a switch statement is no faster than the corresponding if statement, but when the code is compiled, the switch statement can be implemented using a lookup table which is significantly faster than the corresponding if statement.

Example, if the floor is 0, set s to 1, if the floor is prime, add 1, otherwise, subtract 1:

>> s = rand(1)*10;
>> switch floor(s)
  case 0
     s = 1
  case {2, 3, 5, 7}
     s = s + 1
  otherwise
     s = s - 1;
end
>> s              % your result may vary

s =

    0.9872