Detect warning and take action

193 ビュー (過去 30 日間)
Ioannis Nemparis
Ioannis Nemparis 2017 年 11 月 2 日
コメント済み: Rookienp 2019 年 6 月 5 日
I have a for loop and I call a function inside it. What I want to do, is detect if this function call created any warnings and if so continue. Something like:
for i=1:len
c = my_func1(arguments);
if (any warning)
continue;
end
end
Any suggestions? I tried to use lastwarn, without success though.

採用された回答

Cam Salzberger
Cam Salzberger 2017 年 11 月 2 日
Hello Ioannis,
A common workflow is to use lastwarn in this way:
for ...
warning('') % Clear last warning message
... run code ...
[warnMsg, warnId] = lastwarn;
if ~isempty(warnMsg)
...react to warning...
end
end
But you said lastwarn didn't work for you. How did you use it? What do you mean it didn't work? What kind of warnings were you seeing that weren't being picked up?
-Cam
  2 件のコメント
Ioannis Nemparis
Ioannis Nemparis 2017 年 11 月 2 日
I was incorrectly clearing last warning message by doing warnMsg=[] and warnId =[]; Let me experiment a bit with your answer and I will upvote you soon enough
Rookienp
Rookienp 2019 年 6 月 5 日
Suggestion in the Matlab 2018b editor:
WARNING('') does not reset the wanring state, use LASTWARN('') instead.
Both ways work though.

サインインしてコメントする。

その他の回答 (2 件)

Guillaume
Guillaume 2017 年 11 月 2 日
編集済み: Guillaume 2017 年 11 月 2 日
You can treat warnings as errors and thus catch them with a try ... catch statement, however, it is undocumented and may break in a future version. On the other hand, it's been there since 2004.
For more details, see Yair's blog.
However, if you want to catch all warnings, you'll have to set them to error one by one since warning('error') or warning('error', 'all') is not supported, just warning('error', specificmsgid).

M
M 2017 年 11 月 2 日
  1 件のコメント
Ioannis Nemparis
Ioannis Nemparis 2017 年 11 月 2 日
This is mildly related. I do not want to hide a warning message. I want to catch the warning pretty much like an error and do something

サインインしてコメントする。

カテゴリ

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