Search code examples
matlaberror-handlingwarningssuppress-warnings

Matlab - how to catch warning released by cp2tform function


I have a set of N sets of 2D points and I want to parse these N sets in order to find the affine transformation(translation, rotation, scaling including reflexion) with another set q of 2D points.

In order to do so, I am applying the Matlab function cp2tform. However, there are certain scenarios when the function gives me a warning similar to the one illustrated bellow:

Warning: The condition number of A is 117632159740.8394. 
> In maketform>validate_matrix at 328
  In maketform>affine at 163
  In maketform at 129
  In cp2tform>findAffineTransform at 265
  In cp2tform at 168

In these cases, the transformation matrix identified with the cp2tform function does not apply to the real transformation between the 2 sets of 2D points. How can I catch these situations in order to skip them? What matlab function or code should I introduce in order to catch these situations in order to be able to skip or handle them?


Solution

  • Handle Warning:

    As explained here, you could convert specific warnings to errors, and trap those inside a try/catch block.

    Here is an example on how to handle a specific warning (inverting a nearly singular matrix):

    % turn this specific warning into an error
    s = warning('error', 'MATLAB:nearlySingularMatrix'); %#ok<CTPCT>
    
    % invoke code trapping errors
    try
        A = [1 2 3; 4 5 6; 7 8 9];
        B = inv(A);
        disp(B)
    catch ME
        if strcmp(ME.identifier, 'MATLAB:nearlySingularMatrix')
            fprintf('Warning trapped: %s\n', ME.message);
        else
            rethrow(ME);
        end
    end
    
    % restore warning state
    warning(s);
    

    Suppress Warning:

    Of course if you want to suppress a warning message, you could just query the last warning issued using:

    [msgstr, msgid] = lastwarn;
    

    (or use the syntax that @Benoit_11 showed), then turn it off until temporarily inside your function:

    % turn it off
    s = warning('off', msgid);
    
    % ...
    
    % restore state
    warning(s);