MATLAB - Les instructions if imbriquées

Il est toujours légal dans MATLAB d'imbriquer des instructions if-else, ce qui signifie que vous pouvez utiliser une instruction if ou elseif dans une ou plusieurs instructions if ou elseif.

Syntaxe

La syntaxe d'une instruction if imbriquée est la suivante:

if <expression 1>
   % Executes when the boolean expression 1 is true 
   if <expression 2>
      % Executes when the boolean expression 2 is true    
   end
end

Vous pouvez imbriquer elseif ... else de la même manière que vous avez imbriqué l'instruction if.

Exemple

Créez un fichier de script et tapez le code suivant -

a = 100;
b = 200;
   % check the boolean condition 
   if( a == 100 )
   
      % if condition is true then check the following 
      if( b == 200 )
       
         % if condition is true then print the following 
         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 );

Lorsque vous exécutez le fichier, il affiche -

Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200