Skip to main content
Logo image

Subsection If Statement

The simplest if-statement tests a single logical condition. MATLAB evaluates the condition; if it is true, the indented block runs. If it is false, MATLAB skips the block and continues after end.

The if Statement Structure.

Use Case:
if condition is true, run codeBlock.
if condition     % true? ➜ run codeBlock
	codeBlock
end
Notes & Rules:
  • Every if-statement must end with end.
  • condition must be a logical statement that returns true or false.
  • If condition is false, MATLAB does nothing and skips to end.
To see how this works, run the following code block:
Since age is 23, the logical statement age >= 21 is true, so MATLAB executes the fprintf line and prints the message. Now try changing age to 16 and running it again. This time, the age >= 21 is false, so MATLAB skips the fprintf line and nothing is printed.

Checkpoint 27.

(a) What happens when the condition is false?

In a basic if statement, what happens when the condition is false?
  • MATLAB runs the block once and then stops the script.
  • The if statement never stops execution by itself.
  • MATLAB skips the block and continues with the line after end.
  • When the condition is false, MATLAB simply moves past the block.
  • MATLAB runs both the block and the next line after end.
  • Only one path executes: either the block runs or it is skipped.
  • MATLAB reports an error because the condition is false.
  • False conditions are expected, so no error is raised.

(b) Required keyword to close an if statement.

What keyword must appear at the end of every if statement?
  • stop
  • MATLAB does not use stop to close an if statement.
  • end
  • Every if statement must be closed with end.
  • endif
  • MATLAB uses end instead of endif.
  • done
  • MATLAB does not use done to close an if statement.

(c) If statement requires true or false condition.

    The condition in an if statement must evaluate to either true or false.
  • True.

  • A logical condition is a statement that MATLAB evaluates to either true or false, which determines whether the code block executes.
  • False.

  • A logical condition is a statement that MATLAB evaluates to either true or false, which determines whether the code block executes.