Getting Started Previous page   Next Page

Flow Control

MATLAB has several flow control constructs:

if, else, and elseif

The if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The groups of statements are delineated by the four keywords -- no braces or brackets are involved.

The MATLAB algorithm for generating a magic square of order n involves three different cases: when n is odd, when n is even but not divisible by 4, or when n is divisible by 4. This is described by

In this example, the three cases are mutually exclusive, but if they weren't, the first true condition would be executed.

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

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 0's and 1's showing element-by-element equality. (In fact, if A and B are not the same size, then A == B is an error.)

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

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

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.

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


Previous page  Programming switch and case Next page

© 1994-2005 The MathWorks, Inc.