Summary: This is a tutorial on using if statements in MATLAB.
Note: You are viewing an old version of this document. The latest version is available here.
The if statement is one way to make the sequence of computations executed by MATLAB depend on variable values. The if statement has several different forms. The simplest form is
if expression
% MATLAB 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 in MATLAB-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
% MATLAB commands to execute if expression is true
else
% MATLAB 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
% MATLAB commands to execute if expression1 is true
elseif expression2
% MATLAB commands to execute if expression2 is true
elseif expression3
% MATLAB commands to execute if expression3 is true
...
else
% MATLAB 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 MATLAB commands inside the if statement are indented relative to the if, else, elseif, and end statements. This is not required by MATLAB but is common practice and makes the code much more readable.