
4 Programming
Flow Control
In this section.. .
“Conditional Control – if, else, switch” on page 4-2
“Loop Control – for, while, continue, break” on page 4-5
“Error Control – try, catch” on page 4-7
“Program Termination – return” on p age 4-8
Conditional Control – if, else, switch
This section covers those MATLAB functions that provide conditional
program control.
if, else, and elseif
The if statement evaluates a logical expression and executes a gro up of
statements when the expression is tru e .Theoptional
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 gro ups of statements a re delineated by the four keyw ords—no braces or
brackets are involved.
The MATLAB algorithm for generating a m agic 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 divis ible b y 4. This is described by
if rem(n,2) ~= 0
M = odd_magic(n)
elseif rem(n,4) ~= 0
M = single_even_magic( n)
else
M = double_even_magic( n)
end
For most values of n in this examp l e, the th r ee cases are mutually exclusive.
For values that are not mutually exclusive, such as
n=5,thefirsttrue
condition is executed.
4-2
Comentarios a estos manuales