Conditions
In this section we will cover cover conditions which allow to execute a code block only when certain conditions are met.
Conditions in MATLAB generally take one of the following forms:
if-conditions
if-else conditions
if-elseif-else conditions
switch-case conditions
if-condition
The code block is only executed when the condition returns true, otherwise the code block is skipped.
if-else condition
In an if-else condition, if the condition returns true, code block A is executed and the rest is skipped. Otherwise, if the condition returns false, code block B is executed.
if-elseif-else
If the condition is met, code block A is executed and the rest is skipped. Otherwise, if condition B is true, code block B is executed and the rest is skipped. Otherwise, condition C is checked etc... If none of the conditions returns true, the alternative code block in the else part is executed.
Note that it is also possible to nest several conditions to create more complex programs.
To familiarise yourself with if-conditions, consider the following examples. Try changing the value of x and see which statements are executed.
Switch-case conditions
Sometimes we would like to be able to check for many different conditions without writing a lot of if-elseif-else conditions. MATLAB provides the switch-case-otherwise conditions which are particularly useful to check whether a variable takes on a specific value.
Note that the cases can easily contain several valid values as in the case of block B without having to write OR conditions.
Consider the following example.
Note that if we want to check for inequalities, we need to create boolean variables prior to the switch-case-otherwise statement that tell us whether the condition is met. Therefore, in the case of inequalities it is recommended to use if-elseif-else
clauses.
Last updated
Was this helpful?