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.

Syntax

The syntax of an if statement in MATLAB is −

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

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

Example

Create a script file and type the following code −

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' );
   end
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
matlab_decisions.htm
Advertisements