如果发生错误,如何在Matlab中重复for循环迭代
我在MATLAB中有以下代码:如果发生错误,如何在Matlab中重复for循环迭代,matlab,loops,iteration,continue,Matlab,Loops,Iteration,Continue,我在MATLAB中有以下代码: for i = 1: n a = randi([0 500]); function (a); end 当在迭代i=k中执行函数(a)时出现错误,程序停止。有没有办法让程序用新值a重复相同的迭代(当出现错误时)并继续执行?解决问题的方法非常简单。就用吧 用于调用函数的循环 for i=1:3 a=randi([0 500]); try myfunction(a); %Statements that may throw a
for i = 1: n
a = randi([0 500]);
function (a);
end
当在迭代
i=k
中执行函数(a)
时出现错误,程序停止。有没有办法让程序用新值a
重复相同的迭代(当出现错误时)并继续执行?解决问题的方法非常简单。就用吧
用于调用函数的循环
for i=1:3
a=randi([0 500]);
try
myfunction(a); %Statements that may throw an error
catch
%Code that is executed if myfunction throws error
end
disp(i) %Proves that the loop continuous if myfunction throws an error
end
function b = myfunction(a)
b=a;
error('Error!!!') %Function throws error every time it gets called
end
功能
for i=1:3
a=randi([0 500]);
try
myfunction(a); %Statements that may throw an error
catch
%Code that is executed if myfunction throws error
end
disp(i) %Proves that the loop continuous if myfunction throws an error
end
function b = myfunction(a)
b=a;
error('Error!!!') %Function throws error every time it gets called
end
输出而不尝试,捕获
Error using myfunction (line 3)
Error!!!
Error in For_Error (line 6)
myfunction(a); %Statements that may throw an error
1
2
3
用try、catch输出
Error using myfunction (line 3)
Error!!!
Error in For_Error (line 6)
myfunction(a); %Statements that may throw an error
1
2
3
我认为卡斯帕的答案并没有完全回答你的问题,用户3717023。 在Kaspar解决方案中,迭代不会重复,而是简单地跳过(如使用
continue
时)
建议的解决方案
for i=1:3
a=randi([0 500]);
try
myfunction(a); %Statements that may throw an error
catch
%Code that is executed if myfunction throws error
end
disp(i) %Proves that the loop continuous if myfunction throws an error
end
function b = myfunction(a)
b=a;
error('Error!!!') %Function throws error every time it gets called
end
如果希望MATLAB重复迭代直到成功完成myfunction()
,请使用while
。看看这个:
for ii = 1:30
disp(ii)
out = 0;
while(~out)
disp('Attempt ...')
try
out = myfunction(some_arguments);
catch
disp('F****ck!')
end
pause(1)
end
disp('OK !')
end
如果myfunction
返回其输出(如果没有错误就会发生),则在循环时完成。
添加了带有disp
的行以便于自述
运行示例时,添加了带有pause
的行,以获得整洁的输出
示例
使用下面的示例myfunction()
运行上面的代码以检查此解决方案的工作方式:
function out = myfunction(x)
a = randi(2,1,1) - 1; % a = 0 or a = 1
if a==0
error
else
out = magic(3);
end
end
示例输出:
ii =
1
Attempt ...
F****ck!
Attempt ...
OK !
ii =
2
Attempt ...
OK !
ii =
3
Attempt ...
F****ck!
Attempt ...
F****ck!
Attempt ...
F****ck!
Attempt ...
F****ck!
Attempt ...
OK !
最简单的方法是重写函数
,这样它就不会产生错误。其他选项包括使用while
循环和基于函数成功的递增计数器
或语句。使用try/catch
块这样做不是一个好主意。我强烈建议只捕获由函数定义的内容,并重新搜索不匹配的内容。@user3288977
您不必在捕获块中写入任何内容,这取决于可能完全正常的应用程序。在不知道代码应该做什么的情况下,很难提出建议。一种可能是向用户创建一条错误消息,解释异常的原因(请参阅)。据我所知,try/catch
跳过出现错误的迭代并继续循环。。。但是我想在发生错误的地方重新执行相同的迭代。。。我希望这个想法是清楚的