Accelerating the pace of engineering and science

# Documentation Center

• Trial Software

## Control Flow

### Conditional Control — if, else, switch

Conditional statements enable you to select at run time which block of code to execute. The simplest conditional statement is an if statement. For example:

```% Generate a random number
a = randi(100, 1);

% If it is even, divide by 2
if rem(a, 2) == 0
disp('a is even')
b = a/2;
end```

if statements can include alternate choices, using the optional keywords elseif or else. For example:

```a = randi(100, 1);

if a < 30
disp('small')
elseif a < 80
disp('medium')
else
disp('large')
end```

Alternatively, when you want to test for equality against a set of known values, use a switch statement. For example:

```[dayNum, dayString] = weekday(date, 'long', 'en_US');

switch dayString
case 'Monday'
disp('Start of the work week')
case 'Tuesday'
disp('Day 2')
case 'Wednesday'
disp('Day 3')
case 'Thursday'
disp('Day 4')
case 'Friday'
disp('Last day of the work week')
otherwise
disp('Weekend!')
end```

For both if and switch, MATLAB® executes the code corresponding to the first true condition, and then exits the code block. Each conditional statement requires the end keyword.

In general, when you have many possible discrete, known values, switch statements are easier to read than if statements. However, you cannot test for inequality between switch and case values. For example, you cannot implement this type of condition with a switch:

```yourNumber = input('Enter a number: ');

if yourNumber < 0
disp('Negative')
elseif yourNumber > 0
disp('Positive')
else
disp('Zero')
end```

#### Array Comparisons in Conditional Statements

It is important to understand how relational operators and if statements work with matrices. When you want to check for equality between two variables, you might use

`if A == B, ...`

This is valid MATLAB code, and does what you expect when A and B are scalars. But when A and B are matrices, A == B does not test if they are equal, it tests where they are equal; the result is another matrix of 0s and 1s showing element-by-element equality. (In fact, if A and B are not the same size, then A == B is an error.)

```A = magic(4);     B = A;     B(1,1) = 0;

A == B
ans =
0     1     1     1
1     1     1     1
1     1     1     1
1     1     1     1```

The proper way to check for equality between two variables is to use the isequal function:

`if isequal(A, B), ...`

isequal returns a scalar logical value of 1 (representing true) or 0 (false), instead of a matrix, as the expression to be evaluated by the if function. Using the A and B matrices from above, you get

```isequal(A, B)
ans =
0```

Here is another example to emphasize this point. If A and B are scalars, the following program will never reach the "unexpected situation". But for most pairs of matrices, including our magic squares with interchanged columns, none of the matrix conditions A > B, A < B, or A == B is true for all elements and so the else clause is executed:

```if A > B
'greater'
elseif A < B
'less'
elseif A == B
'equal'
else
error('Unexpected situation')
end```

Several functions are helpful for reducing the results of matrix comparisons to scalar conditions for use with if, including

```isequal
isempty
all
any```

### Loop Control — for, while, continue, break

This section covers those MATLAB functions that provide control over program loops.

#### for

The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements:

```for n = 3:32
r(n) = rank(magic(n));
end
r```

The semicolon terminating the inner statement suppresses repeated printing, and the r after the loop displays the final result.

It is a good idea to indent the loops for readability, especially when they are nested:

```for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
end```

#### while

The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements.

Here is a complete program, illustrating while, if, else, and end, that uses interval bisection to find a zero of a polynomial:

```a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x```

The result is a root of the polynomial x3 - 2x - 5, namely

```x =
2.09455148154233```

The cautions involving matrix comparisons that are discussed in the section on the if statement also apply to the while statement.

#### continue

The continue statement passes control to the next iteration of the for loop or while loop in which it appears, skipping any remaining statements in the body of the loop. The same holds true for continue statements in nested loops. That is, execution continues at the beginning of the loop in which the continue statement was encountered.

The example below shows a continue loop that counts the lines of code in the file magic.m, skipping all blank lines and comments. A continue statement is used to advance to the next line in magic.m without incrementing the count whenever a blank line or comment line is encountered:

```fid = fopen('magic.m','r');
count = 0;
while ~feof(fid)
line = fgetl(fid);
if isempty(line) || strncmp(line,'%',1) || ~ischar(line)
continue
end
count = count + 1;
end
fprintf('%d lines\n',count);
fclose(fid);```

#### break

The break statement lets you exit early from a for loop or while loop. In nested loops, break exits from the innermost loop only.

Here is an improvement on the example from the previous section. Why is this use of break a good idea?

```a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x```

### Program Termination — return

This section covers the MATLAB return function that enables you to terminate your program before it runs to completion.

#### return

return terminates the current sequence of commands and returns control to the invoking function or to the keyboard. return is also used to terminate keyboard mode. A called function normally transfers control to the function that invoked it when it reaches the end of the function. You can insert a return statement within the called function to force an early termination and to transfer control to the invoking function.

### Vectorization

One way to make your MATLAB programs run faster is to vectorize the algorithms you use in constructing the programs. Where other programming languages might use for loops or DO loops, MATLAB can use vector or matrix operations. A simple example involves creating a table of logarithms:

```x = .01;
for k = 1:1001
y(k) = log10(x);
x = x + .01;
end```

A vectorized version of the same code is

```x = .01:.01:10;
y = log10(x);```

For more complicated code, vectorization options are not always so obvious.

### Preallocation

If you cannot vectorize a piece of code, you can make your for loops go faster by preallocating any vectors or arrays in which output results are stored. For example, this code uses the function zeros to preallocate the vector created in the for loop. This makes the for loop execute significantly faster:

```r = zeros(32,1);
for n = 1:32
r(n) = rank(magic(n));
end```

Without the preallocation in the previous example, the MATLAB interpreter enlarges the r vector by one element each time through the loop. Vector preallocation eliminates this step and results in faster execution.