第五章--逻辑指令if for ...

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:15

age =

    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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一夕ξ

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

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

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

打赏作者

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

抵扣说明:

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

余额充值