Practical 4: For- and While- Loops, If-statements
Command Sequence Controls
Operators
Relational Operators
Symbol | Example | Meaning of Example |
< | a<6 | true if a is less than 6 |
<= | a<=6 | true if a is less than or equal to 6 |
> | a>6 | true if a is greater than 6 |
>= | a>=6 | true if a is greater than or equal to 6 |
== | a==6 |
true if a is equal to 6 (note double equals sign) |
~= | a~=6 | true if a is not equal to 6 |
Boolean Operators
Symbol | Definition | Example | Meaning of Example |
& | And |
(a>2) & (a<6) |
a is greater than 2 and less than 6 |
| | Or |
(a>2) | (a<6) |
a is less than 2 or greater than 6 |
~ | Not | ~(a==6) | a is not equal to 6 |
Simple if- statements
if <expression>
<commands>…%executed only when
%expression is true
end
Example:
% This code assigns the value of x to negativeValue
% only if x is negative
x = 4;
if x<0
negativeValue = x
end
Exercise: Using Relational Operators > What is wrong with the following code? Type it in MATLAB to check the error message. % This code assigns the value of x to zeroValue only % if x is zero x=4 if x=0 zeroValue = x end > What happens when x equals to zero or x is not zero? |