Environmental Engineering Reference
In-Depth Information
2.6
Ifs and Loops in MATLAB ®
In M-files quite often commands or sequences of commands are to be executed
under certain conditions only. This can be easily programmed using the if ,a
keyword that is available in all programming languages. The following command
sequence in pseudo-programming language explains its application:
If the condition is fulfilled, commands1 are executed. Otherwise commands2 are
executed. The else block can be omitted if there is nothing to be done, if the
condition is not fulfilled. Conditions can be formulated differently. Instead of a
rigorous definition here four mainly self-explaining examples:
In order to be valid conditions, a and b must be of same data type. There are two
equality signs in the first example in order to distinguish a condition from an
assignment. In the second example the condition is clear, if a is a number. But
the condition is also valid if a is of different data type, which the reader may
explore. The last of the four conditions is fulfilled if a is a positive non-zero number,
otherwise not. The letter represents the value of a condition, and could also be
defined like this in MATLAB ® :
By the example sequence the value of a is changed to 1, if the former value was
positive or equal to zero. Variables as c of the example are so-called logicals . These
are variables that can take only two values: 'true' or 'false.' As other programming
languages MATLAB
treats logicals as binary, i.e. they have values 1 for 'true'
®
and 0 for 'false.'
Logical variables can be combined by logical operators (and, or, not and
exclusive or), as given in Table 2.1 . Example:
Search WWH ::




Custom Search