How to Use If Else in MATLAB: Syntax and Examples
In MATLAB, use
if to check a condition and execute code when true, and else to run code when the condition is false. The basic structure is if condition ... elseif condition ... else ... end.Syntax
The if statement tests a condition. If true, it runs the code inside. You can add elseif to check more conditions and else for the default case. Always end with end.
- if condition: Checks if the condition is true.
- elseif condition: Checks another condition if the first is false.
- else: Runs if all above conditions are false.
- end: Closes the if block.
matlab
if condition % code if condition is true elseif another_condition % code if another_condition is true else % code if none of the above conditions are true end
Example
This example checks a number and prints if it is positive, zero, or negative using if, elseif, and else.
matlab
number = -5; if number > 0 disp('The number is positive.') elseif number == 0 disp('The number is zero.') else disp('The number is negative.') end
Output
The number is negative.
Common Pitfalls
Common mistakes include forgetting the end statement, using assignment = instead of comparison ==, and mixing up elseif spelling.
Also, conditions must return logical true or false, not values like strings or numbers directly.
matlab
%% Wrong: missing end if x > 0 disp('Positive') %% Wrong: assignment instead of comparison if x = 5 disp('x is 5') end %% Correct version if x == 5 disp('x is 5') end
Quick Reference
| Keyword | Purpose |
|---|---|
| if | Start a condition check |
| elseif | Check another condition if previous is false |
| else | Run if all conditions are false |
| end | Close the if block |
Key Takeaways
Use
if to run code when a condition is true and else for the false case.Always close your
if block with end.Use
== for comparison, not = which is assignment.You can check multiple conditions using
elseif.Conditions must evaluate to true or false logical values.