if:
>> ther=50;
>> x=input('please enter a number: ');
please enter a number: 40
>> if x>ther
disp('the number is true')
else
disp('the number is not')
end
the number is not
eqx.m:
agethreshold=50;
age=input('please enter your agee:')
if age>agethreshold
disp('wow,getting uo there.')
end
age=input('how old is your brother artemus?:')
if age<12
disp('oh,still a young.')
end
disp('thanks')
>> eqx
please enter your agee:15age =
15
how old is your brother artemus?:5
age =
5
oh,still a young.
thanks
if、elseif、else语句
if <logic expression 1>
<block1>
elseif <logic expression 2>
<block2>
elseif <logic expression 3>
<block3>
else
<block4>
end
&& | AND |
|| | OR |
& | 数组元素与元素AND |
| | 数组元素与元素OR |
~ | not |
== | 等于 |
~= | 不等于 |
>、<、>=、<= | 大于、小于、大于等于、小于等于 |
eqx.m
dice1=randi([1,6])
dice2=randi([1,6])
disp(['dice1:',num2str(dice1),' dice2:',num2str(dice2)])
sum=dice1+dice2
if (dice1==1)&&(dice2==3)
disp('snak eyes')
end
if sum==7
disp('sevens')
elseif (sum==2)||(sum==3)||(sum==12)
disp('craps')
end
>> eqx
dice1 =
4
dice2 =3
dice1:4 dice2:3
sum =
7
sevens
逻辑变量:
其值显示为1或0,逻辑变量有时用作所谓的‘标志’或‘开关’,在程序的一个阶段设置执行来控制后期阶段的行为。
用逻辑变量控制if函数中语句的执行
tperiod=2.3 ymax=1.2 phase=pi/3 tmax=5*tperiod nt=300 gridon=false isdamped=true tau=8.2 t=linspace(0,tmax,nt) y=ymax*cos(2*pi*(t/tperiod)-phase) if isdamped y=y.*exp(-t/tau) end plot(t,y) xlabel('time(s)') ylabel('position(m)') if gridon grid on end
for循环:
重复执行一个指令块,for命令创建一个变量称为’循环变量‘,在其中存储初始值,并在每次执行指令块时递增其值。循环变量通常是整数。
syms k
N=7
for k=1:N
disp(['k= ',num2str(k)])
end
disp('done')
>> eqx
N =
7
k= 1
k= 2
k= 3
k= 4
k= 5
k= 6
k= 7
done
for <index>=<initial value>:<final value>
<block>
end
循环变量的值设置为初始值,然后执行块,之后将索引值增加1,并再次执行该块,直至索引值超过最终值。
for <index>=<initial value>:<increment>:<final value>
<block>
end
改变增值:
syms k
N=10
for k=1:3:N
disp(['k= ',num2str(k)])
end
disp('done')
N =
10
k= 1
k= 4
k= 7
k= 10
done
function n=eqx(x)
n=0
for i=1:1:x
n=n+i
end>>x=100
n=eqx(x)
n=5050