Graphics Programs Reference
In-Depth Information
most computers are accurate to about 16 decimal digits, the loop above
should run until nˆ(-4) is about 10ˆ(-16) , that is, until n is about 10ˆ4 .
Thus the computation will take very little time on most computers. However,
if the exponent were 2 and not 4 , the computation would take about 10ˆ8
operations, which would take a long time on most (current) computers —
long enoughto make it wiser for you to find a more efficient way to sum the
series, for example using symsum if you have the Symbolic Math Toolbox!
Though we have classified it here as a looping command, while also has
features of a branching command. Indeed, the types of expressions allowed
and the method of evaluation for a while statement are exactly the same as
for an if statement. See the section Logical Expressions above for a
discussion of the possible expressions you can put in a while statement.
Breaking from a Loop
Sometimes you may want MATLAB to jump out of a for loop prematurely,
for example if a certain condition is met. Or, in a while loop, there may be an
auxiliary condition that you want to check in addition to the main condition
in the while statement. Inside either type of loop, you can use the command
break to tell MATLAB to stop running the loop and skip to the next line after
the end of the loop. The command break is generally used in conjunction with
an if statement. The following script M-file computes the same sum as in the
previous example, except that it places an explicit upper limit on the number
of iterations:
newsum = 0;
for n = 1:100000
oldsum = newsum;
newsum = newsum + nˆ(-4);
if newsum == oldsum
break
end
end newsum
In this example, the loop stops after n reaches 100000 or when the variable
newsum stops changing, whichever comes first. Notice that break ignores
the end statement associated with if and skips ahead past the nearest end
statement associated witha loop command, in this case for .
Search WWH ::




Custom Search