Matlab-if-elseif-else-statement

提供:Dev Guides
移動先:案内検索

MATLAB-if …​ elseif …​ elseif …​ else …​ endステートメント

*if* ステートメントの後に、1つ(または複数)のオプションの *elseif ...* と *else* ステートメントを続けることができます。これは、さまざまな条件をテストするのに非常に役立ちます。

ifを使用する場合…​ elseif …​ elseステートメント、留意すべき点がいくつかあります-

  • ifには0個または1個のelseを含めることができ、elseifの後に来る必要があります。
  • ifは0個以上のelseifを持つことができ、elseifの前に来る必要があります。
  • else ifが成功すると、残りのelseifもelseもテストされません。

構文

if <expression 1>
   % Executes when the expression 1 is true
   <statement(s)>

elseif <expression 2>
   % Executes when the boolean expression 2 is true
   <statement(s)>

Elseif <expression 3>
   % Executes when the boolean expression 3 is true
   <statement(s)>

else
   %  executes when the none of the above condition is true
   <statement(s)>
end

スクリプトファイルを作成し、その中に次のコードを入力します-

a = 100;
%check the boolean condition
   if a == 10
      % if condition is true then print the following
      fprintf('Value of a is 10\n' );
   elseif( a == 20 )
      % if else if condition is true
      fprintf('Value of a is 20\n' );
   elseif a == 30
      % if else if condition is true
      fprintf('Value of a is 30\n' );
   else
      % if none of the conditions is true '
      fprintf('None of the values are matching\n');
   fprintf('Exact value of a is: %d\n', a );
   end

上記のコードをコンパイルして実行すると、次の結果が生成されます-

None of the values are matching
Exact value of a is: 100