Matlab嵌套if語句

在MATLAB中,嵌套if-else語句是合法的,這意味著可以在一個ifelseif語句中使用另一個ifelseif語句。

語法

嵌套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

可以使用與嵌套if語句相似的方式來嵌套elseif...語句塊。

例子

創建腳本檔並在其中鍵入以下代碼 -

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決策 下一篇: Matlab迴圈