MATLAB 嵌套的 if 语句

返回 MATLAB 决策


在 MATLAB 中嵌套 if-else 语句始终是合法的,这意味着我们可以在另一个 if 或 elseif 语句中使用一个 if 或 elseif 语句。

语法

MATLAB 中 嵌套 if 语句的语法是

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

我们可以嵌套 elseif...else,就像嵌套 if 语句一样。

示例

创建脚本文件并输入以下代码

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 );

当我们运行该文件时,它会显示以下结果

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

返回 MATLAB 决策

查看笔记

扫码一下
查看教程更方便