Kahibaro
Discord Login Register

Control Flow with if, elseif, else

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
end

For 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');
end

Each 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:

  1. Every if block must end with a matching end. Optional elseif and else parts must appear before the end, and else must be last.
  2. Conditions in if and elseif should evaluate to logical values. Use comparison operators like ==, >, <, >=, <=, and ~= instead of using = inside conditions.
  3. MATLAB checks if and elseif conditions from top to bottom and executes only the first true branch. The order of conditions matters.
  4. 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 if block.

Views: 5

Comments

Please login to add a comment.

Don't have an account? Register now!