Repeat Expression in a 'for' loop after try/catch
11 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
woahs
on 19 Jan 2020
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 Comments
Image Analyst
on 19 Jan 2020
Kevin, Can you transfer your "comment" down below to the official "Answers" section?
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!