Summary: This is a tutorial on using if statements in m-file scripts.
The if statement is one way to make the sequence of computations executed by in an m-file script depend on variable values. The if statement has several different forms. The simplest form is
if expression
% Commands to execute if expression is true
end
expression is a logical expression that is either true or false. (Information about logical expressions is available in Programming with M-Files: Logical Expressions.) For example, the following if statement will print "v is negative" if the variable v is in fact negative:
if v < 0
disp('v is negative')
end
A more complicated form of the if statement is
if expression
% Commands to execute if expression is true
else
% Commands to execute if expression is false
end
v is negative and "v is not negative" if v is not negative:
if v < 0
disp('v is negative')
else
disp('v is not negative')
end
The most general form of the if statement is
if expression1
% Commands to execute if expression1 is true
elseif expression2
% Commands to execute if expression2 is true
elseif expression3
% Commands to execute if expression3 is true
...
else
% Commands to execute if all expressions are false
end
if v < 0
disp('v is negative')
elseif v > 0
disp('v is positive')
else
disp('v is zero')
end
Note that in all of the examples in this module, the commands inside the if statement are indented relative to the if, else, elseif, and end statements. This is not required, but is common practice and makes the code much more readable.