Repeat Expression in a 'for' loop after try/catch

조회 수: 19 (최근 30일)
Doheon Lee
Doheon Lee 2020년 1월 19일
댓글: woahs 2020년 1월 19일
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

채택된 답변

woahs
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
Image Analyst 2020년 1월 19일
Kevin, Can you transfer your "comment" down below to the official "Answers" section?
woahs
woahs 2020년 1월 19일
Seems to already be the case?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by