5.2. Control Flow with if, elseif, else
Table of Contents
Why Conditional Control Flow Matters
Conditional control flow lets your code make decisions. Instead of always doing the same thing, your program can choose different actions depending on values, user input, or results of calculations. In MATLAB, the basic building blocks for this kind of decision making are the if, elseif, and else statements.
In this chapter you focus on how to use if, elseif, and else correctly in MATLAB scripts and functions, how MATLAB evaluates the conditions, and how to avoid typical beginner mistakes.
Basic Structure of an if Statement
A simple if statement checks a condition. If the condition is true, MATLAB executes a block of code. If it is false, MATLAB skips that block.
The minimal structure is:
if condition
statements
end
The keyword end closes the if block. Every if must have a matching end. The condition is usually a logical expression that evaluates to true or false.
For example:
x = 10;
if x > 5
disp('x is greater than 5');
end
If x > 5 is true, MATLAB displays the text. If x > 5 is false, MATLAB does nothing and continues after the end.
Using if and else Together
Often you want one block of code when a condition is true and a different block when it is false. This is where else is useful. An else does not have a condition. It runs only if all previous conditions in the if block are false.
The structure is:
if condition
statements_if_true
else
statements_if_false
endFor example:
temperature = 18;
if temperature >= 20
disp('It is warm.');
else
disp('It is not warm.');
end
Here MATLAB either prints "It is warm." or "It is not warm.", but never both, and never neither. Exactly one of the two blocks runs.
Extending Decisions with elseif
Sometimes you want to test several different conditions in order, and run different code for each one. Use elseif for additional conditions after the first if. The elseif keyword must be written as one word.
The general pattern is:
if condition1
statements1
elseif condition2
statements2
elseif condition3
statements3
else
statements_otherwise
end
You can have zero, one, or many elseif parts, but at most one else part, and if you use else it must be last.
A typical example that categorizes a value:
score = 72;
if score >= 90
grade = 'A';
elseif score >= 80
grade = 'B';
elseif score >= 70
grade = 'C';
elseif score >= 60
grade = 'D';
else
grade = 'F';
end
disp(grade);
MATLAB checks the conditions from top to bottom and executes only the first block whose condition is true. After that, it skips the rest of the chain and jumps to the end.
Order of Conditions and Short-Circuiting
The order of the if and elseif conditions is very important. MATLAB evaluates them in sequence. As soon as it finds a true condition, it executes the corresponding block and ignores all later elseif and else parts.
In the grading example above, if score is 95, only the first condition (score >= 90) matters. Since that is true, MATLAB never checks score >= 80, and so on.
This behavior means you must order your conditions so that earlier ones are more specific or higher priority when needed. For example:
x = 5;
if x > 0
disp('Positive');
elseif x > 10
disp('Greater than 10'); % This is never reached for x > 10
end
For any x > 10, the first condition x > 0 is already true, so the elseif x > 10 block is never executed. To make the second condition effective, you must check the more specific case first.
Truth Values in if Conditions
Inside an if, elseif, or else chain, MATLAB expects the condition to be a logical value. The most common sources of logical values are relational comparisons, such as >, <, ==, >=, <=, and ~=.
For example:
x = 3;
if x == 3
disp('x equals 3');
end
The expression x == 3 is true when x is 3 and false otherwise.
MATLAB also accepts numeric values in if conditions. In that case, zero is treated as false and any nonzero value is treated as true. For instance:
value = 0;
if value
disp('This will not display');
end
value = 2;
if value
disp('This will display');
end
For clarity, beginners should usually prefer explicit logical conditions such as value ~= 0 instead of relying on the numeric interpretation of truth.
Using Logical Operators inside Conditions
Conditions can be combinations of simpler logical expressions connected with logical operators, for example && for logical AND and || for logical OR. These operators appear inside the if line, not as separate statements.
A typical combined condition:
x = 5;
if (x > 0) && (x < 10)
disp('x is between 0 and 10');
end
If both parts (x > 0) and (x < 10) are true, then the whole condition is true. If either one is false, the combined condition is false and the block is skipped.
Logical operators can make conditions more expressive and compact. At the same time, very long combined conditions can be hard to read, so you may sometimes split a complicated check into multiple steps and then use an if on the result.
Matching if, elseif, else, and end
MATLAB uses indentation and matching keywords to make conditional blocks clear. The interpreter itself relies on matching pairs of if and end. An elseif or else always belongs to the most recent unmatched if above it.
This matching means you must not accidentally write an extra end or forget to close an if. For example, this is correct:
value = -3;
if value > 0
disp('Positive');
elseif value < 0
disp('Negative');
else
disp('Zero');
endEach keyword is on its own line, and the blocks under them are indented. MATLAB does not require indentation, but using it consistently makes matching much easier for you and anyone who reads your code.
If you open several if blocks inside each other, each one still needs its own end. MATLAB and the Editor will help by auto-indenting and by showing vertical lines to connect if and end.
Nesting if Statements
Sometimes one decision depends on the result of another. In that situation, you can place an entire if block inside another if, elseif, or else block. This is called nesting.
Here is a simple nested structure:
x = 7;
y = -2;
if x > 0
if y > 0
disp('x and y are both positive');
else
disp('x is positive, y is not positive');
end
else
disp('x is not positive');
end
The inner if block only runs if the outer condition x > 0 is true. If x is not positive, MATLAB never checks y > 0. Each nested if requires its own end.
Nesting is powerful but can become hard to follow when it gets too deep. If you find yourself with many levels of nested if blocks, you may later refactor the code into simpler conditions or separate functions, but for now, understanding how nesting behaves is enough.
if Blocks and Variable Assignment
Variables that you assign inside an if, elseif, or else block are created in the current workspace only when that block of code actually runs. If execution skips that block, then those assignments never happen.
For example:
x = 3;
if x > 5
result = 'large';
else
result = 'small or equal';
end
disp(result);
No matter which branch runs, result is assigned a value, so it is always defined after the if block.
However, if not all branches assign to the same variable, you might end up with a variable that does not exist, or has different types in different cases. For instance:
x = 10;
if x > 0
msg = 'positive';
end
disp(msg);
This works only when x > 0. If x is zero or negative, the body of the if never runs, so msg is never created. Then the final disp(msg) causes an error. To avoid this, make sure that all possible paths either assign the variable or that you give it an initial value before the if block.
A better version:
x = -1;
msg = 'not positive';
if x > 0
msg = 'positive';
end
disp(msg);
Now msg always exists and always has some defined value.
Common Errors with if, elseif, else
Beginners often encounter a few typical mistakes when using conditional statements. Recognizing them early can save time.
One common issue is writing else if instead of elseif. MATLAB uses a single word elseif. If you write else if, MATLAB treats it as two separate keywords, which changes how the block is interpreted. The correct pattern is:
if condition1
...
elseif condition2
...
end
Another mistake is forgetting the end so an if block is not properly closed. In that case MATLAB shows an error about unexpected end of file or missing end. Always check that each if has exactly one corresponding end.
A further source of confusion is the use of the assignment operator = instead of the equality operator == in conditions. For example:
x = 3;
if x = 5 % This is invalid
disp('x is 5');
end
This code is incorrect, because x = 5 is an assignment, not a comparison. MATLAB raises a syntax error. You must write:
if x == 5
disp('x is 5');
end
Finally, if a condition returns something that is not a scalar logical, such as a vector of logical values, MATLAB may show an error or a warning, depending on the context. For most if statements you should use a single logical value, not a whole array.
Using if, elseif, else in Simple Designs
In beginner scripts, if, elseif, and else already let you implement many simple algorithms. For example, you can respond differently to user input, classify numbers into categories, guard against invalid values, or perform a calculation only when a condition holds.
A short example that uses a simple decision:
radius = -3;
if radius <= 0
disp('Radius must be positive');
else
area = pi * radius^2;
disp(area);
end
Here the if block protects the calculation from a nonsensical value of radius. This kind of basic input checking is a common and practical use of conditional control flow.
You will later combine if statements with loops and functions to build more complete programs, but the rules described in this chapter remain the same.
Key points to remember:
- Every
ifblock must end with a matchingend. Optionalelseifandelseparts must appear before theend, andelsemust be last. - Conditions in
ifandelseifshould evaluate to logical values. Use comparison operators like==,>,<,>=,<=, and~=instead of using=inside conditions. - MATLAB checks
ifandelseifconditions from top to bottom and executes only the first true branch. The order of conditions matters. - Variables assigned only inside a branch exist only if that branch runs. Ensure that important variables are assigned on all possible paths or initialized before the
ifblock.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Getting Started with MATLAB
- ☰ 1.1. What Is MATLAB and What Is It Used For
- ☰ 1.2. Installing MATLAB and Setting Up the Environment
- ☰ 1.3. Understanding the MATLAB Desktop Interface
- ☰ 1.4. Command Window, Workspace, and Current Folder
- ☰ 1.5. Basic Workflow and Running Simple Commands
- ☰ 1.6. Getting Help and Documentation
-
- ☰ 2. MATLAB Language Basics
- ☰ 2.1. MATLAB Syntax and Expressions
- ☰ 2.2. Variables and Assignment
- ☰ 2.3. Data Types and Type Conversion
- ☰ 2.4. Vectors and Matrices Fundamentals
- ☰ 2.5. Creating and Indexing Arrays
- ☰ 2.6. Basic Arithmetic and Elementwise Operations
- ☰ 2.7. Using Built-In Constants and Functions
-
- ☰ 3. Working with Variables and the Workspace
- ☰ 3.1. Creating, Viewing, and Editing Variables
- ☰ 3.2. Workspace Browser and Variable Inspector
- ☰ 3.3. Saving and Loading Data Files
- ☰ 3.4. MAT-Files and Importing External Data
- ☰ 3.5. Clearing Variables and Managing the Workspace
-
- ☰ 4. Vectors, Matrices, and Arrays
- ☰ 4.1. Row and Column Vectors
- ☰ 4.2. Matrix Creation and Concatenation
- ☰ 4.3. Indexing, Slicing, and Logical Indexing
- ☰ 4.4. Matrix Operations vs Elementwise Operations
- ☰ 4.5. Reshaping and Rearranging Arrays
- ☰ 4.6. Special Matrices and Functions
-
- ☰ 5. Basic Programming Constructs
- ☰ 5.1. Scripts vs Functions
- ☰ 5.2. Control Flow with if, elseif, else
- ☰ 5.3. Loops with for and while
- ☰ 5.4. break, continue, and return
- ☰ 5.5. Logical Expressions and Relational Operators
- ☰ 5.6. Best Practices for Clear and Readable Code
-
- ☰ 6. Functions in MATLAB
- ☰ 6.1. Creating Simple Functions
- ☰ 6.2. Function Inputs and Outputs
- ☰ 6.3. Function Files and the Path
- ☰ 6.4. Local vs Global Variables
- ☰ 6.5. Anonymous Functions
- ☰ 6.6. Organizing Code into Multiple Functions
-
- ☰ 7. Working with Numbers and Math
- ☰ 7.1. Scalars and Vectorized Computations
- ☰ 7.2. Basic Mathematical Functions
- ☰ 7.3. Trigonometric and Exponential Functions
- ☰ 7.4. Complex Numbers in MATLAB
- ☰ 7.5. Rounding, Modulo, and Special Values
- ☰ 7.6. Numerical Precision and Floating Point Considerations
-
- ☰ 8. Strings, Characters, and Categorical Data
- ☰ 8.1. Character Arrays and String Arrays
- ☰ 8.2. Creating and Manipulating Strings
- ☰ 8.3. Converting Between Data Types and Strings
- ☰ 8.4. Comparing and Searching Strings
- ☰ 8.5. Categorical Arrays Basics
-
- ☰ 9. Tables, Structures, and Cell Arrays
- ☰ 9.1. Introduction to Tables
- ☰ 9.2. Creating Tables and Accessing Data
- ☰ 9.3. Modifying and Joining Tables
- ☰ 9.4. Structures and Nested Structures
- ☰ 9.5. Cell Arrays and Cell Indexing
- ☰ 9.6. Choosing the Right Container Type
-
- ☰ 10. Importing and Exporting Data
- ☰ 10.1. Reading Text and CSV Files
- ☰ 10.2. Importing Excel Spreadsheets
- ☰ 10.3. Importing Data with the Import Tool
- ☰ 10.4. Exporting Data to Files
- ☰ 10.5. Working with Image and Audio Files
- ☰ 10.6. Basic File Management from MATLAB
-
- ☰ 11. Plotting and Visualization
- ☰ 11.1. Introduction to 2D Plotting
- ☰ 11.2. Customizing Plots and Axes
- ☰ 11.3. Multiple Plots in One Figure
- ☰ 11.4. Labels, Titles, Legends, and Annotations
- ☰ 11.5. Plotting with Different Line and Marker Styles
- ☰ 11.6. Saving and Exporting Figures
-
- ☰ 12. Advanced Plotting for Beginners
- ☰ 12.1. Subplots and Tiled Layouts
- ☰ 12.2. Bar, Scatter, and Stem Plots
- ☰ 12.3. Histograms and Density Plots
- ☰ 12.4. 3D Plots and Surface Plots
- ☰ 12.5. Using plottools and Interactive Editing
- ☰ 12.6. Basics of Handle Graphics
-
- ☰ 13. Working with Scripts and Live Scripts
- ☰ 13.1. Creating and Running Script Files
- ☰ 13.2. Sectioning Code and Running Sections
- ☰ 13.3. Live Scripts and Rich Text
- ☰ 13.4. Adding Equations, Images, and Outputs
- ☰ 13.5. Sharing and Exporting Live Scripts
-
- ☰ 14. Debugging and Code Quality
- ☰ 14.1. Finding and Fixing Syntax Errors
- ☰ 14.2. Setting Breakpoints and Stepping Through Code
- ☰ 14.3. Inspecting Variable Values During Execution
- ☰ 14.4. Using the Editor Debugging Tools
- ☰ 14.5. Using Code Analyzer and Warnings
- ☰ 14.6. Writing Clean and Maintainable MATLAB Code
-
- ☰ 15. Basic Linear Algebra with MATLAB
- ☰ 15.1. Vectors and Norms
- ☰ 15.2. Matrix Addition and Multiplication
- ☰ 15.3. Solving Linear Systems with Backslash
- ☰ 15.4. Inverses, Determinants, and Rank
- ☰ 15.5. Eigenvalues and Eigenvectors
- ☰ 15.6. Using Linear Algebra Functions Safely
-
- ☰ 16. Data Analysis and Statistics Fundamentals
- ☰ 16.1. Descriptive Statistics and Summary Measures
- ☰ 16.2. Sorting, Filtering, and Grouping Data
- ☰ 16.3. Basic Correlation and Regression
- ☰ 16.4. Simple Data Cleaning Techniques
- ☰ 16.5. Basic Time Series Handling
-
- ☰ 17. Working with Time and Dates
- ☰ 17.1. Representing Dates and Times
- ☰ 17.2. Creating and Formatting datetime Arrays
- ☰ 17.3. Date Calculations and Differences
- ☰ 17.4. Plotting Data over Time
-
- ☰ 18. Introduction to Signal and Image Handling
- ☰ 18.1. Basic Signal Representation in MATLAB
- ☰ 18.2. Simple Filtering and Transformations
- ☰ 18.3. Reading, Displaying, and Writing Images
- ☰ 18.4. Basic Image Transformations
-
- ☰ 19. Automation and Scripting Tasks
- ☰ 19.1. Batch Processing of Files
- ☰ 19.2. Writing Reusable Utility Scripts
- ☰ 19.3. Using Relative Paths and the MATLAB Path
- ☰ 19.4. Simple User Interaction with input and disp
-
- ☰ 20. Introduction to Toolboxes
- ☰ 20.1. What Are Toolboxes and How to Use Them
- ☰ 20.2. Exploring Installed Toolboxes
- ☰ 20.3. Finding Functions in Toolboxes
- ☰ 20.4. Add-Ons and MATLAB File Exchange
-
- ☰ 21. Best Practices and Next Steps
- ☰ 21.1. Organizing Projects and Folders
- ☰ 21.2. Version Control Basics with MATLAB
- ☰ 21.3. Performance Tips for Beginners
- ☰ 21.4. Learning Resources and Documentation Path
- ☰ 21.5. Suggested Practice Projects for Beginners
-
Comments
Please login to add a comment.
Don't have an account? Register now!