Practical 4: For- and While- Loops, If-statements
Command Sequence Controls
if Statements
Complex if-elseif-else-end statements:
if <expression 1>
<command> % evaluated if expression 1 is true
elseif <expression 2>
<command> % evaluated if expression 2 is true
elseif expression3
<command> % evaluated if expression 3 is true
….
else
<command> % evaluated if none of expressions are true
end
Example:
% If x is negative, assign value of x to negativeValue
% If x is positive, assign value of x to positiveValue
% If x is zero, assign value of x to zeroValue
x=4
if x<0
negativeValue = x
elseif x>0
positiveValue = x
else
zeroValue = x
end
Exercise: Using if- statements > Verify that the above code is correct by checking with a positive, negative and zero value of x. It will be faster to run the code from a script M-file. > Why don’t we need to check if x is actually zero when assigning it to zeroValue? |