English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MATLAB Nested if Statements

MATLAB Conditional Statements

Nested if in MATLAB-The else statement is always legal, which means you can use if or elseif statements within another if or elseif statement.

Syntax

The syntax of nested if statements is as follows-

if <expression 1>
   %When the boolean expression1Executes when true 
   if <expression 2>
      %When the boolean expression2Executes when true
   end
end

You can nest elseif ... else, just like nested if statements.

Online Example

Create a script file and type the following code in it-

a = 100;
b = 200;
   %Check boolean condition
   if( a == 100)
   
      %Check the following content if condition is true
      if( b == 200)
       
         %Print the following content if condition is true
         fprintf('Value of a is 100 and b is 200\n');
      end
       
   end
   fprintf('Exact value of a is: %d\n', a);
   fprintf('Exact value of b is: %d\n', b);
It displays when the file is run-
Value of a is 100 and b is 200
Exact value of a is: 100
Exact value of b is: 200

MATLAB Conditional Statements