Skip to main content
v2026.11,858 entries · CC-BY 4.0
LAC HealthMedical & Research SuppliesReagents, PPE & instruments — chain-of-custody documented.Fast, traceable sourcing built for regulated research environments, from bench consumables to instrumentation.Shop lac.us CodeCASRAIlac.us

If-Else in MATLAB: if, elseif, else Syntax with Examples

MATLAB if, elseif, else syntax with worked examples, the elseif vs else if pitfall, array-condition rules and free alternatives.

Written and maintained by CASRAI Editorial Board

Last updated

An if-else in MATLAB is written if, elseif, else, end. The branch runs only when its condition is true, and elseif is one word: writing else if with a space opens a second, nested if that needs its own end. This page is for researchers and analysts who need to branch on data (thresholds, missing values, string options) and want the array-condition and operator rules that most short answers skip.

What it is used for in research

Conditional statements let a script choose what to do depending on the data in front of it. Typical research uses are applying a different processing step above or below a threshold, skipping a file whose dimensions do not match the others, and selecting an analysis path from a text option. Repeating a step over many files or samples is the job of a loop; see loops in MATLAB and combine the two when each iteration needs a decision.

Install or access (official source only)

MATLAB is a commercial product from MathWorks, available through mathworks.com or through your institution’s MathWorks account if it has one. The if statement is part of the core MATLAB language, so no toolbox is needed. For a wider orientation to the product, see what MATLAB is used for.

Step-by-step: write an if, elseif, else block

1. Use the documented syntax

The MathWorks reference gives this form. elseif and else are optional, and you can use several elseif branches.

if expression
    statements
elseif expression
    statements
else
    statements
end

2. Run a first example

x = 7;
if x < 0
    disp('negative')
elseif x == 0
    disp('zero')
else
    disp('positive')
end

MATLAB tests the conditions from the top and runs only the first branch whose condition is true. Here x < 0 and x == 0 are false, so the else branch prints positive.

3. Combine conditions with && and ||

MathWorks advises using && and || inside if conditions, not & and |. Inside an if condition the single-character forms short-circuit like the double forms, but the double forms make the intent consistent. The documentation’s range check has this shape:

if (x >= minVal) && (x <= maxVal)
    disp('x is in range')
end

Short-circuiting also lets you guard a second test that would fail if the first is false. The documentation’s example only calls myfunction if the file exists:

x = 42;
if exist('myfunction.m','file') && (myfunction(x) >= pi)
    disp('Expressions are true')
end

“elseif” versus “else if”, the common pitfall

Both MATLAB and GNU Octave document this: elseif is one keyword. With a space, the second if is nested inside the else branch, and every if needs its own end. The Octave manual adds that elseif “must not be spelled else if” and warns that, when run from a file, the mismatch can produce errors or wrong results.

Intended code What MATLAB reads
if x < 0
    disp('negative')
elseif x == 0
    disp('zero')
else
    disp('positive')
end
One if with a second condition, closed by one end.
if x < 0
    disp('negative')
else if x == 0
    disp('zero')
else
    disp('positive')
end
end
An if whose else branch contains a nested if. It needs two end keywords; with only one, the outer block is left open.

Prefer the first form. It stays flat however many branches you add, and the number of end keywords stays at one.

Output and how to read it

An if block produces no output of its own; what you see is whatever the executed branch does, such as a disp call or an assignment. If nothing appears, no condition was true and there was no else. To see which branch ran, add a disp or fprintf call in each branch while debugging.

Array conditions: what “true” means

Per the MathWorks reference, an expression is true when its result is nonempty and contains only nonzero elements; otherwise it is false. Two consequences matter for data analysis.

A comparison on an array is true only if every element passes

Wrap the comparison in any to test whether at least one element passes, or in all to make the every-element rule explicit.

signal = [0.2 0.9 0.4];
limit = 0.8;
if any(signal > limit)
    disp('At least one sample exceeds the limit')
else
    disp('All samples are within the limit')
end

Here signal > limit is [0 1 0]. Used directly it would be false because not all elements are nonzero, while any returns true and the first branch runs. For more on the arrays being tested, see matrices in MATLAB.

An empty result is false

If a condition evaluates to an empty array, the branch does not run and no error is raised. That can hide a mistake such as a filter that matched no rows, so check isempty explicitly when emptiness is meaningful.

Comparing text and whole arrays

Do not use == for these cases. The MathWorks reference states that == on character vectors of different sizes results in an error, and that it errors on arrays of different sizes.

  • Character vectors: use strcmp(reply,'y').
  • Whole arrays: use isequal, for example if isequal(size(A),size(B)) before concatenating A and B.
  • Not equal: use ~= for numeric comparison.

Alternatives inside MATLAB

The documentation notes that logical indexing is often faster than an if inside a loop, so for “apply to every element above a threshold” prefer an index such as signal(signal > limit) = limit; over looping with a conditional. When one variable selects among many discrete values, a switch statement can be clearer than a long elseif chain. If you wrap a conditional in a small function, see anonymous functions in MATLAB.

Troubleshooting

Symptom Likely cause and fix
Error about missing or extra end else if was typed instead of elseif, creating a nested block. Use elseif.
Error comparing text with == Character vectors of different sizes cannot be compared with ==. Use strcmp.
Error comparing two arrays Their sizes differ. Check with isequal(size(A),size(B)) first.
Branch never runs on array data Not every element is nonzero, or the result is empty. Use any, all or isempty as intended.

Free alternatives

Tool Keywords for the same structure Source
MATLAB if, elseif, else, end MathWorks documentation
GNU Octave (free software) if, elseif, else, closed with endif; matrix conditions are true only if non-empty and all elements are nonzero Octave manual, The if Statement
Python (free software) if, elif, else; “elif” is short for “else if” Python tutorial, section 4.1

FAQ

What is the syntax for if else if in MATLAB?

Write if condition, then elseif condition, then optionally else, and finish with a single end. You can include several elseif branches.

Is it “else if” or “elseif” in MATLAB?

It is elseif, one word. else if with a space starts a nested if that requires its own end.

How do I test two conditions at once?

Join them with && for “and” or || for “or”, which MathWorks recommends in if conditions.

Why does my if on an array not run?

A condition on an array is true only when the result is nonempty and every element is nonzero. Use any or all to state what you mean.

Can I use if-else in a loop?

Yes. Put the conditional inside the loop body. If the loop only applies a threshold, logical indexing may be simpler and faster, per the MathWorks documentation. See loops in MATLAB.

Sources

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about If-Else in MATLAB: if, elseif, else Syntax with Examples

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →