Environmental Engineering Reference
In-Depth Information
Fig. 2.9 Illustration of a loop
, there are several
other types of loops. Another main type is the while -loop. Here a condition is
checked at the start of the loop, and the commands of the loop (between while and
end statements) are executed as long as the condition is fulfilled. Here the use has to
take care that some of the variables appearing in the condition change during the
loop; otherwise an infinite loop in produced.
If in larger loops it is necessary to have another outlet from the loop aside from the
default at the end , one may use the break command. In nested loops the command
only concerns that one loop, in which the statement is placed, i.e. execution proceeds
with the command after the next end of loop statement.
continue is a related command: the execution is skipped not for the entire
concerned loop (as with break ), but only for the remaining statements in the current
run through the loop.
Loops can also be used in the MATLAB
Like in any other programming language, also in MATLAB
®
command mode. A trivial example is:
®
Note that no prompt appears after pressing the return key. The command is not
yet executed. Enter:
When the end command is entered the entire loop is executed and the prompt
appears in the command window again. Note that in the specification of the loop
variable i only two values are given. The increment 1 is used as default in such a
situation.
In MATLAB ® the direct notation of loops can often be avoided by using vector-
or vector-matrix notations. For an example examine the 'elegant' solution
implementing the Horner scheme, as shown above. By matrix-vector multiplica-
tion loops are implicitly performed, as there is a sum over the products of matrix
elements. Utilizing this type of looping not only is much shorter and more clearly
Search WWH ::




Custom Search