Repeat Expression in a 'for' loop after try/catch
11 次查看(过去 30 天)
显示 更早的评论
I have try/catch lines inside a 'for' loop as below. What I want is to repeat index 'i' if an error is encountered. However, 'i' keeps increasing to the next number depsite a line 'i = i -1'.
For example, when an error occured at i = 5, 'i' became 4 after on line 'i = i - 1'. However, it changed to i = 6 at Expression1. Please help with this. Thank you in advance.
for i = 1:10
Expression1
try
Expresssion2
catch ME
if strcmp(ME.message, '****')
data(i) = [];
end
i = i-1;
end
end
0 个评论
采纳的回答
woahs
2020-1-19
You shouldn't be changing the loop variable i in a for loop.
Normally, the loop variable is incremented at the end of the loop. No idea what you have in Expression1 and Expression2 but if you want to to know the index when an error occurs, you can just access it normally in the catch. The following code gives the resulting output:
for i = 1:10
fprintf('Current i = %d\n', i);
try
if(i == 5)
error('error')
end
catch ME
fprintf('Error at i = %d\n', i);
end
end
Current i = 1
Current i = 2
Current i = 3
Current i = 4
Current i = 5
Error at i = 5
Current i = 6
Current i = 7
Current i = 8
Current i = 9
Current i = 10
3 个评论
Image Analyst
2020-1-19
Kevin, Can you transfer your "comment" down below to the official "Answers" section?
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!