repeat the iteration with an error using try/catch

I wrote a nested for loop to exexcute a huge number of iterations. However, sometimes an error stops the program. I want to repeat the iEv'th iteration in case an error occurs and then continue to next iteration. Please see below the code and let me know if it should be modified.
for iTcm=1:nTcm
for iScen=1:nScen
for iEv=1:nEv
try
MyProgramHere
catch ME
disp(ME);
fprintf('Retrying the program...\n');
end
end
end
end

 採用された回答

James Tursa
James Tursa 2020 年 4 月 3 日
編集済み: James Tursa 2020 年 4 月 3 日

0 投票

Maybe this construct does what you want
while( true )
try
MyProgramHere
break
catch ME
disp(ME);
fprintf('Retrying the program...\n');
end
end

3 件のコメント

Mos_bad
Mos_bad 2020 年 4 月 3 日
James if you mean the following code, yes it works. I added iEv = iEv - 1 after cath ME.
My concern is if an error occurs within the iEv'th iteration, is the iEv'th iteration repeated? or the program skips the iEvth iteration where the error occurs and goes to next iteration (iEv+1)?
for iTcm=1:nTcm
for iScen=1:nScen
for iEv=1:nEv
while (true)
try
MyProgram
break
catch ME
iEv = iEv - 1;
disp(ME);
fprintf('Retrying the program...\n');
end
end
end
end
end
Mos_bad
Mos_bad 2020 年 4 月 3 日
This code didn't work either. Any help?
James Tursa
James Tursa 2020 年 4 月 3 日
編集済み: James Tursa 2020 年 4 月 4 日
No. I meant exactly what I wrote, without this line:
iEv = iEv - 1; % delete this line
By getting rid of this line, it will keep repeating the same iteration indefinitely until it passes. iEv doesn't change until you do the iteration successfully. If you want a limit on the number of tries before you generate an error then additional code would need to be added.

サインインしてコメントする。

その他の回答 (1 件)

darova
darova 2020 年 4 月 3 日
編集済み: darova 2020 年 4 月 3 日

0 投票

My proposition
for iTcm=1:nTcm
for iScen=1:nScen
iEv = 0;
while iEv <= nEv
iEv = iEv + 1;
try
MyProgramHere
catch ME
iEv = iEv-1;
disp(ME);
fprintf('Retrying the program...\n');
end
end
end
end

4 件のコメント

Mos_bad
Mos_bad 2020 年 4 月 3 日
The suggested code does not work.
darova
darova 2020 年 4 月 3 日
How is it possible? Can you be more specific?
darova
darova 2020 年 4 月 3 日
What about this. I improved my code
Mos_bad
Mos_bad 2020 年 4 月 3 日
With the improved code, when the iEv count reaches to nEv, the program control goes immediately to the catch block. So the program stops without going to (iScen+1)th iteration.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2020 年 4 月 3 日

編集済み:

2020 年 4 月 4 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by