MATLAB - if... end Statement

An if ... end statement consists of an if statement and a boolean expression followed by one or more statements. It is delimited by the end statement.


The syntax of an if statement in MATLAB is −

if <expression>
   % statement(s) will execute if the boolean expression is true 

If the expression evaluates to true, then the block of code inside the if statement will be executed. If the expression evaluates to false, then the first set of code after the end statement will be executed.

Flow Diagram

MATLAB if statement


Create a script file and type the following code −

Live Demo
a = 10;
% check the condition using if statement 
   if a < 20 
   % if condition is true then print the following 
      fprintf('a is less than 20\n' );
fprintf('value of a is : %d\n', a);

When you run the file, it displays the following result −

a is less than 20
value of a is : 10