Matlab:如何捕捉警告

l5tcr1uw  于 2023-10-23  发布在  Matlab
关注(0)|答案(3)|浏览(231)

我在MATLAB中运行一些数据处理工作,求解器使用了SLASH运算符。有时候,我会收到这样的警告:

  1. Warning: Rank deficient, rank = 1390, tol = 1.335195e-010.
  2. Warning: Rank deficient, rank = 1386, tol = 1.333217e-010.

我想听听这些警告。我试图将警告转换为错误,然后按照标题“捕获警告”下的描述捕获它:http://undocumentedmatlab.com/blog/trapping-warnings-efficiently在示例中,以下字符串用于将warning转换为error:

  1. s = warning('error', 'MATLAB:DELETE:Permission');

但是,我不确定我的情况下使用什么字符串。我尝试使用

  1. s = warning('error', 'Warning: Rank deficient’);

但是,它没有工作。如果你能帮忙的话,我将不胜感激。
问候,DK

mfuanj7w

mfuanj7w1#

您需要指定警告 * 标识符 *,而不是警告文本。您可以使用lastwarn的双输出形式找到标识符:

  1. [msgstr, msgid] = lastwarn

在你的例子中,我认为你想要的标识符是'MATLAB:rankDeficientMatrix'

igetnqfo

igetnqfo2#

您可以尝试使用lastwarn作为替代方案。除法之后,调用它并将其与strcmp和通常的警告消息进行比较,如果是您想要的,您可以手动抛出error所需的错误。
正如你所建议的:你可以重置lastwarn抛出一个空的警告warning('')

ig9co6j1

ig9co6j13#

下面的代码紧密地实现了Python的

  1. with warnings.catch_warnings(record=True) as ws:
  2. fn_out = fn()
  3. warn_out = ''
  4. for w in ws:
  5. if 'blah' in w.message:
  6. warn_out = w.message

它执行fn()两次,确保警告状态被恢复,并可选地抑制其打印语句(例如,disp)。要求warning()语句使用警告ID,即warning('a:b', msg)语法。

示例

  1. fn = @()delete('beep'); % target function
  2. warn_id = 'MATLAB:DELETE:FileNotFound'; % target warning ID
  3. o = execute_and_catch_warning(fn, warn_id); % application
  4. [fn_out, warn_out] = o{:} % fetch function output and warning message
  1. fn_out =
  2. NaN
  3. warn_out =
  4. 'File 'beep' not found.'

分步骤

1.存储warning状态以便以后恢复
1.将warning('off', warn_id)设置为允许执行而不显示警告
1.执行fn()以获取其输出
1.设置warning('error', warn_id),以便下次执行fn()时触发警告,但不打印它
1.再次执行fn()
1.通过e.messagecatch e)消除警告
1.恢复警告状态
1.以out = {fn_out, warn_out}的形式返回fn()的输出和警告消息
更多的事情发生了(例如)。try-catch)但这是想法。
fn_out可以是可选的(例如,添加另一个arg,并使用if get_outputs Package 代码)。

代码

  1. function [fn_out, warn_out] = execute_and_catch_warning(fn, warn_id) %#ok<INUSD>
  2. s = warning;
  3. warning('off', warn_id);
  4. try
  5. % first try assuming `fn()` has an output
  6. [~, fn_out] = fn();
  7. catch
  8. % this is in case `fn()` has no output
  9. warning(s); % restore prematurely in case `fn()` errors again
  10. fn();
  11. fn_out = nan;
  12. end
  13. warning('error', warn_id);
  14. try
  15. fn(); % suppress print statements
  16. warn_out = "";
  17. catch e
  18. warn_out = e.message;
  19. end
  20. warning(s) % restore warning state
  21. end

抑制打印:将fn()替换为evalc('fn()')。* (通常不鼓励使用eval,但docs中的任何内容都不适用)。*

展开查看全部

相关问题