
一条if语句后可以跟一个(或多个)可选elseif...和一条else语句,这对于测试各种条件非常有用。
当使用if ... elseif ... else语句时,要牢记以下几点:
一个if可以有零个或另一个,并且必须在其他elseif之后。
一个if可以具有零个或多个elseif,并且它们必须位于else之前。
如果else if成功,则不会测试其余的elseif。
语法
if <expression 1> %当表达式1为true时执行 <statement(s)> elseif <expression 2> %当布尔表达式2为true时执行 <statement(s)> Elseif <expression 3> %当布尔表达式3为true时执行 <statement(s)> else %当上述条件都不为true时执行 <statement(s)> end
在线示例
创建一个脚本文件并在其中键入以下代码-
a = 100;
%检查布尔条件
if a == 10
%如果condition为真,则打印以下内容
fprintf('Value of a is 10\n' );
elseif( a == 20 )
% 如果条件成立的话
fprintf('Value of a is 20\n' );
elseif a == 30
% 如果条件成立的话
fprintf('Value of a is 30\n' );
else
%如果没有一个条件是真的
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