Graphics Programs Reference
In-Depth Information
➱
Using
while
, one can easily end up accidentally creating an “infinite
loop”, one that will keep running indefinitely because the condition
you set is never met. Remember that you can generally interrupt
the execution of such a loop by typing
CTRL+C;
otherwise, you may
have to shut down MATLAB.
Open-Ended Loops
Here is a simple example of a script M-file that uses
while
to numerically
sum the infinite series 1
/
1
4
+
1
/
2
4
+
1
/
3
4
+···
, stopping only when the terms
become so small (compared to the machine precision) that the numerical sum
stops changing:
n=1;
oldsum = -1;
newsum = 0;
while newsum > oldsum
oldsum = newsum;
newsum = newsum + nˆ(-4);
n=n+1;
end
newsum
Here we initialize
newsum
to
0
and
n
to
1
, and in the loop we successively
add
nˆ(-4)
to
newsum
, add
1
to
n
, and repeat. The purpose of the variable
oldsum
is to keep track of how much
newsum
changes from one iteration
to the next. Each time MATLAB reaches the end of the loop, it starts over
again at the
while
statement. If
newsum
exceeds
oldsum
, the expression in
the
while
statement is true, and the loop is executed again. But the first
time the expression is false, which will happen when
newsum
and
oldsum
are
equal, MATLAB skips to the
end
statement and executes the next line, which
displays the final value of
newsum
(the result is
1.0823
to five significant
digits). The initial value of
-1
that we gave to
oldsum
is somewhat arbitrary,
but it must be negative so that the first time the
while
statement is executed,
the expression therein is true; if we set
oldsum
to
0
initially, then MATLAB
would skip to the
end
statement without ever running the commands in the
loop.
Even though you can construct an M-file like the one above without deciding
exactly how many times to run the loop, it may be useful to consider roughly
how many times it will need to run. Since the floating point computations on
Search WWH ::
Custom Search