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

7 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by