Matlab中的 if else语句详解

if else语句的表达形式为:

if condition      如果condition的logical为true1 则执行action1,
                  如果logical为false2 则执行action2
   
   action1
   
else
 
  action2
  
end

例:输入一个半径,如果该半径小于0,则输出:对不起该半径不是一个合适的值,如果半径大于0,则输出该圆的面积。

radius=input('please input a radius: ')
if radius < 0
fprintf('sorry this radius %f is not a approporate value',radius) 
else
area = pi * radius^2
end

例:描述一个分段函数当:
x<-1时,y=1;
-1<= x <=2时,y=x^2
x>2时,y=4

用if语句来实现时:

% x<-1时,y=1;
% -1<= x <=2时,y=x^2
% x>2时,y=4
x=input('please input a number: ')
if x < -1
    y=1
end
if x >=-1 && x <=2
    y=x^2
end
if x>2
    y=4
end

用 if…else 语句来实现时:

% x<-1时,y=1;
% -1<= x <=2时,y=x^2
% x>2时,y=4
x=input('please input a number: ')
if x < -1
    y=1
else            % x >= -1
if  x <=2
    y=x^2
else            % x>2
    y=4
end

上面的else和if也可以直接放在一起:

% x<-1时,y=1;
% -1<= x <=2时,y=x^2
% x>2时,y=4
x=input('please input a number: ')
if x < -1
    y=1
elseif  x <=2
    y=x^2
else
    y=4
end

例:写一个函数,该函数可以考察输入的部分是否是一个标量、向量还是矩阵。scalar、vector、matrix。
首先可以分析一下标量、向量、矩阵的分别的特点。

%分别编辑几个标量、向量和矩阵 
a1=0;
a2=5;
b1=[0 1 3];
b2=[0 1 3 5 6];
c1=[1 2 3;1 2 4];
c2=[1 2 3 5;1 5 2 4;4 7 5 6;6 8 7 8];
%查看它们的特点
whos

在这里插入图片描述
可见标量的行和列都是1、向量的行都是1列都非1、矩阵的行和列都非1

x=input('please input a Scalar、Vector or Matrix:')
[r,c]=size(x);
if r==1 && c==1
disp('x is a "Scalar"')
end
if r==1 && c~=1
disp('x is a "Vector"')
end
if r~=1 && c~=1
disp('x is a "Matrix"')
end

用else语句来实现:

x=input('please input a Scalar、Vector or Matrix:')
[r,c]=size(x);
if r==1 && c==1
disp('x is a "Scalar"')
elseif r==1 
disp('x is a " Row Vector"')
elseif c==1
disp('x is a " Column Vector"')
else
disp('x is a "Matrix"')
end
  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

华毓

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

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

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

打赏作者

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

抵扣说明:

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

余额充值