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