MATLAB 的if...elseif...elseif...else...end语句中if语句可以跟随一个(或多个)可选的elseif... else语句,这是非常有用的,可以用来对各种条件进行测试。
使用if... elseif...elseif...else语句,要注意以下几点:
一个 if 可以有零个或多个 else,但是它必须跟在elseif 后面(即只有 elseif 存在才会有 else)。
一个 if 可以有零个或多个 elseif,必须出现else。
一旦 elseif 匹配成功,余下的 elseif 将不会被测试。
if... elseif...else...end语法:
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
详细例子如下:
在MATLAB中建立一个脚本文件,并输入下述代码:
a = 100;%check the boolean condition if a == 10 % if condition is true then print the following fprintf('Value of a is 10' );elseif( a == 20 )% if else if condition is true fprintf('Value of a is 20' );elseif a == 30 % if else if condition is true fprintf('Value of a is 30' );else% if none of the conditions is true 'fprintf('None of the values are matching');fprintf('Exact value of a is: %d', a );end
编译和执行上述代码,产生如下结果:
None of the values are matchingExact value of a is: 100