MATLAB has several flow control constructs:
if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional
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 legal MATLAB code, and does what you expect when
B are scalars. But when
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
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
Here is another example to emphasize this point. If
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
|Programming with MATLAB||switch and case|