如何在 Matlab 中捕获警告?
How to catch warning in Matlab?
我正在使用 Matlab 的 distfit 函数对我的数据进行概率分布拟合。有时会出现以下警告信息:
Maximum likelihood estimation did not converge. Iteration limit
exceeded
在这种情况下,分布是拟合的(负对数似然不是复杂的或无限的)但拟合非常差(高 AIC)。
如果出现此警告,如何在 Matlab 中进行检查?如果出现这样的警告,我想抛出一个错误(并捕获它)。
目前,我正在调查负对数似然是复数还是无限,如果是,我将抛出一个错误。我还应该做其他检查吗?
您不能直接捕捉到警告,但可以通过使用以下构造
关闭给出的警告消息来伪装它
% reset warnings
lastwarn('');
% Do your fitting
<your code here>
% Check which warning occured (if any)
[msgstr, msgid] = lastwarn;
switch msgid
case 'ThisParticularMessageID'
% In your case you say you want to throw an error
error(msgstr); % or your custom error message
%case 'SomeOtherMessageIDIfYouWantToCheckForSomethingElse'
end
棘手的事情是找到正确的 msgid。最简单的方法是使用现有代码,在看到警告消息后,在命令行类型
[msgstr,msgid] = lastwarn
这会告诉你你想为 'ThisParticularMessageID'
使用什么。
使用未记录的语法 warning('error', 'mycomponent:myMessageID')
将告诉 MATLAB 将警告转换为错误,然后您可以使用 try-catch
块捕获并适当处理:
您可以在警告发生后使用 lastwarn
找到警告的消息 ID。
我正在使用 Matlab 的 distfit 函数对我的数据进行概率分布拟合。有时会出现以下警告信息:
Maximum likelihood estimation did not converge. Iteration limit exceeded
在这种情况下,分布是拟合的(负对数似然不是复杂的或无限的)但拟合非常差(高 AIC)。
如果出现此警告,如何在 Matlab 中进行检查?如果出现这样的警告,我想抛出一个错误(并捕获它)。
目前,我正在调查负对数似然是复数还是无限,如果是,我将抛出一个错误。我还应该做其他检查吗?
您不能直接捕捉到警告,但可以通过使用以下构造
关闭给出的警告消息来伪装它% reset warnings
lastwarn('');
% Do your fitting
<your code here>
% Check which warning occured (if any)
[msgstr, msgid] = lastwarn;
switch msgid
case 'ThisParticularMessageID'
% In your case you say you want to throw an error
error(msgstr); % or your custom error message
%case 'SomeOtherMessageIDIfYouWantToCheckForSomethingElse'
end
棘手的事情是找到正确的 msgid。最简单的方法是使用现有代码,在看到警告消息后,在命令行类型
[msgstr,msgid] = lastwarn
这会告诉你你想为 'ThisParticularMessageID'
使用什么。
使用未记录的语法 warning('error', 'mycomponent:myMessageID')
将告诉 MATLAB 将警告转换为错误,然后您可以使用 try-catch
块捕获并适当处理:
您可以在警告发生后使用 lastwarn
找到警告的消息 ID。