Graphics Programs Reference
In-Depth Information
real part is treated as true, while numbers with zero real part are treated as
false. Furthermore, if the expression evaluates to a vector or matrix, an
if
or
elseif
statement must still result in a single true-or-false decision. The
convention MATLAB uses is that all elements must be true (i.e., all elements
must have nonzero real part) for an expression to be treated as true. If any
element has zero real part, then the expression is treated as false.
You can manipulate the way branching is done with vector input by in-
verting tests with
~
and using the commands
any
and
all
. For example, the
statements
if x == 0; ...; end
will execute a block of commands (rep-
resented here by
···
) when all the elements of
x
are zero; if you would like
to execute a block of commands when
any
of the elements of
x
is zero you
could use the form
if x
~
= 0; else; ...; end
. Here
~
=
is the relational
operator for “does not equal”, so the test fails when any element of
x
is zero,
and execution skips past the
else
statement. You can achieve the same effect
in a more straightforward manner using
any
, which outputs true when any
element of an array is nonzero:
if any(x == 0); ...; end
(remember
that if any element of
x
is zero, the corresponding element of
x==0
is
nonzero). Likewise
all
outputs true when all elements of an array are
nonzero.
Here is a series of examples to illustrate some of the features of logical
expressions and branching that we have just described. Suppose you want to
create a function M-file that computes the following function:
sin(
x
)
/
xx
=
0
,
1
x
=
0
.
f
(
x
)
=
You could construct the M-file as follows:
function y = f(x)
ifx==0
y=1;
else
y = sin(x)/x;
end
This will work fine if the input
x
is a scalar, but not if
x
is a vector or matrix.
Of course you could change
/
to
./
in the second definition of
y
, and change
the first definition to make
y
the same size as
x
. But if
x
has both zero and
nonzero elements, then MATLAB will declare the
if
statement to be false and
use the second definition. Then some of the entries in the output array
y
will
be
NaN
, “not a number,” because
0/0
is an indeterminate form.
Search WWH ::
Custom Search