MATLAB Answers

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

조회 수: 8(최근 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
catch ME
if strcmp(ME.message, '****')
data(i) = [];
i = i-1;

채택된 답변

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);
if(i == 5)
catch ME
fprintf('Error at i = %d\n', i);
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
woahs 2020년 1월 19일
Seems to already be the case?

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

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by