matlab - 由于matlab中'if'语句中的'continue'语句导致循环问题
问题描述
我有以下代码在执行时无限运行。如果我删除 CONTINUE 语句就可以了。但是,使用 CONTINUE 语句会出现问题。代码是
Bn_x=zeros (length(pu_arrival), 1); Bn_x(1)=6;
Br_x=zeros (length(pu_arrival), 1); Br_x(1)=2;
jn1= zeros (length(pu_arrival), 1); jn1(1)=3;
in=zeros (length(pu_arrival), 1);
jn2= zeros (length(pu_arrival), 1); jn2(1)=3;
jr1=zeros (length(pu_arrival), 1); jr1(1)=1;
ir=zeros (length(pu_arrival), 1);
jr2=zeros (length(pu_arrival), 1); jr2(1)=1;
numb_chan_idle_N=0;
numb_chan_idle_R=0;
for i=2:24 %length(pu_arrival)
if rem(i,2)==0
[Bn_x,Br_x]=failure3(numb_chan_idle_N,numb_chan_idle_R,in,jn1,jn2,ir,jr1,jr2,Bn_x,Br_x,i);
continue
end
end
%%%%%%%%被调用函数%%%%%%%%%%%%
function [Bn_x,Br_x] =failure3(numb_chan_idle_N,numb_chan_idle_R,in,jn1,jn2,ir,jr1,jr2,Bn_x,Br_x,i)
temp=0;
while temp<1
x=randi([1 6]);
if x==1
if in(i-1)>0
temp=temp+1;
end
elseif x==2
y=randi([1 2]);
if y==1
if jn1(i-1)>0
temp=temp+1;
end
elseif y==2
if jn2(i-1)>0
temp=temp+1;
end
end
elseif x==3
if ir(i-1)>0
end
elseif x==4
y=randi([1 2]);
if y==1
if jr1(i-1)>0
temp=temp+1;
end
elseif y==2
if jr2(i-1)>0
temp=temp+1;
jr2(i)=jr2(i-1)-1;
Br_x(i)=Br_x(i-1)-1;
else
fprintf('JR2 destined to fail but it is already=%d\n', jr2(i-1))
continue
end
end
elseif x==5
if numb_chan_idle_N>0
temp=temp+1;
end
elseif x==6
if numb_chan_idle_R>0
temp=temp+1;
end
end
end
end
我希望控制器在满足 IF 条件并执行其内部语句后返回 FOR 循环。但是,控制器永远不会出来。我无法弄清楚代码有什么问题。
解决方案
您正在内部生成无限循环fault3
, continue 语句按预期工作,代码永远不会到达它。
在您给出的代码中,只有某些输入相关条件会导致temp=temp+1
退出的必要条件failure3
。某些数字组合(例如您作为示例提供的数字)永远不会触发if
内部的任何条件failure3
,因此永远不会退出。
通过将以下内容添加到代码中,您可以轻松地看到这一点:
function [Bn_x,Br_x] =failure3(numb_chan_idle_N,numb_chan_idle_R,in,jn1,jn2,ir,jr1,jr2,Bn_x,Br_x,i)
temp=0;
iteration = 0
while temp<1
iteration=iteration +1
...
背后的逻辑failure3
被打破了。无论如何,只要你有一个无限循环while temp<1
,尝试添加一个额外的语句,while temp<1 && iteration<500
这样你就可以更好地调试代码。
推荐阅读
- date - 如何在 GStreamer 视频流上显示日期(文本叠加)?
- r - 构建一个迭代其他数据帧的大数据帧
- azure - iOS xamarin - 在应用内购买时首次启动时崩溃
- sqlite - 将数据从 Oracle (SQL Developer) 移动到 MS SQL Server 的有效方法
- html - 关于 create-react-app 的初学者问题:先完成 HTML/CSS,然后添加到应用程序
- r - 在 for 循环期间设置数据帧的子集时,我得到一个零行数据帧而不是预期的一行?
- authentication - 具有动态客户端注册的 OAuth2 资源所有者密码凭证
- python - 使用 xml 作为数据发布请求给出错误 415
- angular - 登录后导航到选项卡时如何修复“错误:无法匹配任何路由”?
- css - :focus-within 聚焦第一个孩子而不是最后一个孩子