Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch warning in Matlab?

I'm using the distfit function of Matlab to fit a probability distribution to my data. Sometimes the following warning message appears:

Maximum likelihood estimation did not converge. Iteration limit exceeded

In this case the distribution is fitted (the negative log likelihood is not complex or infinite) but the fit is very bad (high AIC).

How can I check in Matlab if this warning appears? If such a warning appears I want to throw an error (and catch it).

Currently, I'm investigating if the neagtive log likelihood is complex or infinite and if so, I'm throwing an error. Are there other checks which I should do?

like image 627
machinery Avatar asked Apr 22 '26 11:04

machinery


2 Answers

You can't directly catch a warning, but can fake it by keying off the warning message being given by using the following construct

% 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

The tricky thing is finding the correct msgid. The easiest way is to use your existing code, and after you see the warning message, at the Command Line type

[msgstr,msgid] = lastwarn

That will tell you what you want to use for 'ThisParticularMessageID'.

like image 170
Phil Goddard Avatar answered Apr 25 '26 12:04

Phil Goddard


Using the undocumented syntax warning('error', 'mycomponent:myMessageID') will tell MATLAB to convert the warning to an error, which you can then catch with a try-catch block and handle appropriately:

You can find the message ID for your warning using lastwarn just after it occurs.

like image 31
Sam Roberts Avatar answered Apr 25 '26 12:04

Sam Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!