MATLAB if...elseif...elseif...else...end 语句

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 matching
Exact value of a is: 100

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

std86021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值