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

MATLAB if Statement: Syntax, and/or/not, Arrays

How the MATLAB if statement works: syntax, not/and/or/equal conditions, array and empty rules, and a MATLAB versus GNU Octave table.

Written and maintained by CASRAI Editorial Board

Last updated

Quick answer: in MATLAB, if runs a block of statements only when its condition is true, with optional elseif and else branches and a closing end. A condition counts as true when its result is nonempty and contains only nonzero elements; an empty result is false. This page is for researchers and analysts who need to write correct conditions, including ones that combine tests (and, or, not), compare values, or receive arrays. If you are specifically looking for the elseif and else branches, the else if versus elseif distinction and multi-branch examples, see If-Else in MATLAB: if, elseif, else syntax with examples; this page focuses on how MATLAB evaluates the condition itself.

What the if statement is used for in research code

Analysis scripts branch constantly: apply a correction only when a sample size passes a threshold, skip a file when a field is missing, choose a processing path by data type. The if statement is MATLAB’s conditional for those decisions. To repeat work across many items, pair it with the loops covered in Loops in MATLAB: for, while and how to stop them; to select elements of an array without writing a loop at all, the MathWorks documentation notes that logical indexing often outperforms if and loops.

Access: where the official syntax lives

The authoritative reference is the MathWorks documentation page for if (mathworks.com/help/matlab/ref/if.html, read 2026-11-07). The same keyword exists in the free GNU Octave language, documented at docs.octave.org, The if Statement (v9.2.0, read 2026-11-07); the differences are tabulated below.

Step-by-step: writing an if statement

Syntax

The documented form is:

if expression
    statements
elseif expression
    statements
else
    statements
end

elseif and else are optional, and you may use several elseif branches.

  1. Write the condition. Start with if followed by an expression that evaluates to a logical or numeric result.
  2. Add the statements to run when the condition is true.
  3. Add alternatives if needed with elseif expression for further tests and a final else for everything else.
  4. Close the block with end. Each nested if needs its own end.
  5. Write elseif as one word. Typing else if with a space creates a nested if inside else, which then needs an extra end.

MATLAB if not

Use ~ for logical not, and ~= for “not equal”, for example if ~isempty(x) or if a ~= b.

MATLAB if and / MATLAB and if (multiple conditions)

Combine tests with && (and) and || (or). A range check from the MathWorks examples has the form if (x >= minVal) && (x <= maxVal), optionally followed by an elseif for the remaining cases. Inside an if condition, the single operators & and | short-circuit the same way as && and ||, but the documentation recommends && and || for consistency.

MATLAB if a or b

Write if a || b. Short-circuiting matters when the second operand would produce an error: the documentation’s example tests exist('myfunction.m','file') first so that the function is only called when the file exists.

MATLAB if equal

For scalars, == compares values. For arrays, the documentation prefers isequal, because == errors when the two arrays differ in size. For character vectors, use strcmp.

MATLAB for if

Placing an if inside a for loop is ordinary nesting: the loop supplies each value and the if tests it, with each construct closed by its own end.

Output: how MATLAB reads the condition

An if produces no value of its own; what you read is which branch ran. The branch depends on how the condition is judged true or false:

Condition result Treated as What to use instead if you meant something else
Nonempty, all elements nonzero (logical or real numeric) True Not applicable
Empty False Test isempty explicitly if emptiness matters
Nonscalar array True only if every element is nonzero any(...) to test whether at least one element is true, for example if any(A > limit)
Comparing two arrays with == Errors if sizes differ isequal(A,B)
Comparing character vectors Documentation example uses strcmp strcmp

This is why a “matrix if” often surprises people: if A > 0 on a vector runs only when all elements pass.

Troubleshooting

  • Missing end error or code running in the wrong place: count the end keywords against every if, and check you did not type else if with a space.
  • Branch not running for an array: every element must be nonzero; use any or all deliberately.
  • Error when comparing arrays: switch from == to isequal.
  • Error from the second half of an or/and test: use short-circuit && or || and put the guarding test first.
  • Generating C/C++/GPU code: the documentation says not to use & or | in if conditions for code generation, and that HDL Coder does not support nonscalar conditions, so reduce with all or any.
  • Selecting elements: if the goal is to filter an array, logical indexing often outperforms if with loops, and the same condition ideas carry over to anonymous functions and cell array handling.

Free alternatives: GNU Octave

GNU Octave documentation (v9.2.0, read 2026-11-07) describes the same construct with these differences from the MATLAB documentation:

Point MATLAB GNU Octave
Block terminator end endif (or end)
Array condition True only if nonempty and all elements nonzero True only if nonempty and all elements nonzero (equivalent to all(matrix(:)))
Else-if spelling Use elseif; else if creates a nested if elseif must not be spelled else if

For wider comparisons of the two environments for research, see MATLAB vs R.

FAQ

How do I write “if not” in MATLAB?

Use the ~ operator, as in if ~condition, or ~= for inequality between two values.

How do I test multiple conditions in one if?

Join them with && or ||, or chain branches with elseif.

How do I check equality in an if?

Use == for scalars, isequal for arrays and strcmp for character vectors.

What does if A do when A is a matrix?

It is true only when A is nonempty and every element is nonzero. Use any to test for at least one nonzero element.

Can I write else if with a space?

You can, but it creates a nested if that needs its own end. Write elseif to continue the same block.

Sources (official documentation)

Related CASRAI guides: Fit in MATLAB, MATLAB LineStyle.

Follow CASRAI

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

Ask CASRAI · free to try

Ask about MATLAB if Statement: Syntax, and/or/not, Arrays

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 →