Search code examples
matlabsuppress-warnings

MATLAB Warnings under fmincon


I'm minimizing a function with the fmincon routine.

This function uses the integral command several times. However, some of those integrals turns out to be Inf or NaN and I don't want MATLAB to show a warning when this happens (the function is always finite).

I've tried using the command warning('off','MATLAB:integral:NonFiniteValue') but it don't seem to be working when running the optimization.


Solution

  • It could be you're simply suppressing the wrong message. You could inspect the values of

    [a,b] = lastwarn
    

    inside an output function (opts = optimset('OutputFcn', @myOutFcn);) to make 100% sure you're killing the correct warning message.

    But I too have encountered this annoying behavior before -- you just can't seem to suppress certain warnings in MATLAB's own functions. For those, you have to resort to ugly and fragile hacks.

    You could try

    warning off
    ... 
    warning on
    

    which suppresses all warnings for all code contained in the '...' section.

    You could also use an undocumented feature: temporarily promote the warning to an error:

    ws = warning('error', 'MATLAB:integral:NonFiniteValue');
    ...
    warning(ws);
    

    and wrap it up in a try....catch. Chances are you then interrupt integral and thus fmincon prematurely and will thus have to wrap it up together with some rescue mechanism, but that gets real complicated and real ugly real fast, so that's only to be used as a last resort...

    ...so in all, it's easiest to just live with the warnings.