Graphics Programs Reference
In-Depth Information
function y = absval(x)
y=x;
ify<0
y = -y;
end
The elseif statement is useful if there are more than two alternatives
and they can be distinguished by a sequence of true/false tests. It is essen-
tially equivalent to an else statement followed immediately by a nested if
statement.Intheexamplebelow,weuse elseif inanM-file signum.m ,which
evaluates the mathematical function
1 x > 0 ,
0 x = 0 ,
1 x < 0 .
sgn( x ) =
(Again, MATLAB has a built-in function sign that performs this function for
more general inputs than we consider here.)
function y = signum(x)
ifx>0
y=1;
elseif x == 0
y=0;
else
y = -1;
end
Here if the input x is positive, then the output y is set to 1 and all commands
from the elseif statement to the end statement are skipped. (In particular,
the test in the elseif statement is not performed.) If x is not positive, then
MATLABskipstothe elseif statementandteststoseeif x equals 0 .Ifso, y is
set to 0 ; otherwise y is set to -1 . Notice that MATLAB requires a double equal
sign == to test for equality; a single equal sign is reserved for the assignment
of values to variables.
Like for and the other programming commands you will encounter, if and
its associated commands can be used in the Command Window. Doing so can
be useful for practice with these commands, but they are intended mainly for
use in M-files. In our discussion of branching, we consider primarily the case
of function M-files; branching is less often used in script M-files.
Search WWH ::




Custom Search