Graphics Programs Reference
In-Depth Information
Branching with if
For a simple illustration of branching with if , consider the following function
M-file absval.m , which computes the absolute value of a real number:
function y = absval(x)
ifx>=0
y=x;
else
y = -x;
end
The first line of this M-file states that the function has a single input x and
a single output y . If the input x is nonnegative, the if statement is deter-
mined by MATLAB to be true. Then the command between the if and the
else statements is executed to set y equal to x , while MATLAB skips the
command between the else and end statements. However, if x is negative,
then MATLAB skips to the else statement and executes the succeeding com-
mand, setting y equal to -x . As witha for loop, the indentation of commands
above is optional; it is helpful to the human reader and is done automatically
by MATLAB's built-in Editor/Debugger.
Most of the examples in this chapter will give peculiar results if their input
is of a different type than intended. The M-file absval.m is designed only
for scalar real inputs x , not for complex numbers or vectors. If x is complex
for instance, then x>=0 checks only if the real part of x is nonnegative,
and the output y will be complex in either case. MATLAB has a built-in
function abs that works correctly for vectors of complex numbers.
In general, if must be followed on the same line by an expression that
MATLAB will test to be true or false; see the section below on Logical Expres-
sions for a discussion of allowable expressions and how they are evaluated.
After some intervening commands, there must be (as with for ) a correspond-
ing end statement. In between, there may be one or more elseif state-
ments (see below) and/or an else statement (as above). If the test is true,
MATLAB executes all commands between the if statement and the first
elseif , else ,or end statement and then skips all other commands un-
til after the end statement. If the test is false, MATLAB skips to the first
elseif , else ,or end statement and proceeds from there, making a new test
in the case of an elseif statement. In the example below, we reformulate
absval.m so that no commands are necessary if the test is false, eliminating
the need for an else statement.
Search WWH ::




Custom Search