Environmental Engineering Reference
In-Depth Information
There is also the possibility for a direct multiple branching. For this purpose
MATLAB@ has the switch - case construction. It is exemplified in the following
examples:
In order to use the functionality of a single M-file for the example from the
preceding section, the programming technique of loops has to be applied. How
loops work, is best explained by an example. The most common for -loop is used in
the command sequence:
for is a MATLAB
keyword, which is indicated by a different color.
®
MATLAB
keywords may not be used as variable names. The statement, starting
with the for keyword, starts a loop, which ends at the line with the end keyword.
lambda is the loop variable in this example (the user is free to choose the name of
the variable). In the first run through the loop lambda has the value 1.
The commands within the loop are executed with that parameter value; here the
function vector f is evaluated and a graph is plotted in the figure. Then the
commands are executed again with the variable parameter taking the next value.
In the example lambda gets the values 2, 3, 4 and finally 5. After the last run through
the loop the execution continues with the next statement after end . In the example
after the loop, the final command adds the legend in the figure. As described in
Sect. 2.5 store the entire M-file under a new name and call that name in the
®
command window; or use the
button (old version:
(Fig. 2.9 )).
Note that commands within loops are indented, as shown in the example above.
This is not required by MATLAB
, but it is highly recommended, as it enhances
the readability of the M-files significantly. Loops may be nested, i.e. inner loops
may appear within outer loops. In that case it is important to recognize the
corresponding end statements. It is good practise to indent commands with every
inner loop even further. In that way the programmer visually obtains a connection
between the start of a loop (with either a for or a while keyword) and the
corresponding end .
®
Search WWH ::




Custom Search