MATLAB Programming/Control Flow

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Control Flow[edit | edit source]

IF statement[edit | edit source]

An IF statement can be used to execute code when the logical test (expression) returns a true value (anything but 0). An "else" statement following an "if" statement is executed if the same expression is false (0).


if expression
elseif expression2

SWITCH statement[edit | edit source]

Switch statements are used to perform one of several possible sets of operations, depending on the value of a single variable. They are intended to replace nested "if" statements depending on the same variable, which can become very cumbersome. The syntax is as follows:

switch variable
    case value1
    case value2

The end is only necessary after the entire switch block, not after each case. If you terminate the switch statement and follow it with a "case" statement you will get an error saying the use of the "case" keyword is invalid. If this happens it is probably because you deleted a loop or an "if" statement but forgot to delete the "end" that went with it, thus leaving you with surplus "end"s. Thus MATLAB thinks you ended the switch statement before you intended to.

The otherwise keyword executes a certain block of code (often an error message) for any value of variable other than those specified by the "case" statements.

Programmers who are used to C style languages, often put break statements after each case. In C, C++, and Java, not putting a break statement allows the code to fall through in the code above, if value1 is true, then statements(1), statements(2), etc., will execute in C-style languages. However, in MATLAB only statements(1) will execute.

TRY/CATCH statement[edit | edit source]

The TRY/CATCH statement executes a certain block of code in the "try" block. If it fails with an error or a warning, the execution of this code is terminated, and the code in the "catch" block is executed rather than simply reporting an error to the screen and terminating the entire program. This is useful for debugging and also for filtering out erroneous calculations, like if you accidentally try to find the inverse of a singular matrix, when you don't wish to end the program entirely.



Note that unlike the other control flow statements, the TRY/CATCH block does not rely on any conditions. Therefore the code in the TRY block will always be at least partially executed. Not all of the TRY block code will always be executed, since execution of the TRY ends when an error occurs. In addition, the statements in the CATCH block will never be executed if the TRY block does not fail.

FOR statement[edit | edit source]

The FOR statement executes code a specified number of times using an iterator. Syntax:

for iterator = startvalue:increment:endvalue

The iterator variable is initialized to startvalue and is increased by the amount in increment every time it goes through the loop, until it reaches the value endvalue. If increment is omitted, it is assumed to be 1, as in the following code:

for ii = 1:3

This would execute statements three times.

WHILE statement[edit | edit source]

The while statement executes code until a certain condition evaluates to false or zero. Example:

while condition

Forgetting to change the condition within a while loop is a common cause of infinite loops.

BREAK, CONTINUE, and RETURN[edit | edit source]

MATLAB includes the "break" and "continue" keywords to allow tighter loop control. The "break" keyword will cause the program to leave the loop it is currently in and continue from the next line after the loop ends, regardless of the loop's controlling conditions. If the code is in a nested loop it only breaks from the loop it's in, not all of them. The syntax is simply to write the word "break" within the loop where you desire it to break.

In contrast to "break", "continue" causes the program to return to the beginning of the loop it is presently in, and to recheck the condition to see if it should continue executing loop code or not. The code in the loop after the "continue" statement is not executed in the same pass.

If you want to exit a function entirely (as opposed to just a loop) before the last line of code, it is possible to do so using the "return" keyword. The value of any output variables is immediately returned to the calling function. As an example of how this works, consider the following function:

function output = controlTest(doWhat)
switch doWhat
  case 1
     output = -1;
  case 2
     output = 3;
output = output + 4;


>> output = controlTest(1) 

would return output = -1, because output is defined to -1 and the return statement tells MATLAB to immediately take the current value of output and pass it back to the calling function. However, calling

>> output = controlTest(2) 

would return output = 7, because output is initially defined as 3 and then 4 is added to it. Since the return statement is only executed in the case that doWhat=1, it is not called and the rest of the function executes.

Beware that if the output variables are not defined before calling the return statement, you will get an error, so use this with some degree of caution.