This tutorial is going to help us understand the working of the if, elseif, else statements in MATLAB.
Understanding if, elseif, and else Statement in MATLAB
if, elseif, and else are conditional statements used in MATLAB to execute a specific portion of the code under the given conditions. When we have more than two conditions, we use if, elseif, and else statements. Here, the if statement executes the first condition, elseif executes the second condition, and others, and, else executes whenever any condition is not satisfied.
The Syntax for if, elseif, and else Statements in MATLAB
The if, elseif, else statements follow a simple syntax in MATLAB:
statements
elseif expression2
statements
else
statements
end
In the above syntax:
The if block gets executed whenever expression1 evaluates to be true. The statements within this block will run when the result of expression1 is not empty and consists of non-zero real or logical elements.
The elseif block is used to specify additional conditions to check. If expression1 is false, MATLAB moves on to evaluate expression2. If expression2 is true, the statements within the elseif block will execute.
The else block is executed whenever all specified conditions are false. The statements within this block will run when none of the preceding conditions evaluate to be true.
The end keyword ends the entire if, elseif, else statement.
Example 1
This MATLAB code accepts a number from the user and determines whether the number is positive, negative, or, zero using the if, elseif, and else statement.
Example 2
This MATLAB code accepts a number from the user and determines whether the number lies between the specified interval using the if, elseif and else statement.
Conclusion
The if, elseif, and else statement in MATLAB is used for testing the given conditions in the program. Every statement has its own block of code and executes whenever its specified condition gets satisfied. Here, the if statement executes the first condition, elseif executes the second condition and others, and, else executes whenever any conditions are not satisfied. This tutorial helped us understand the working of the if, elseif, and else statements in MATLAB using some examples.