matlabvalidationassertassertion

Assert Success in Matlab Without Using Classes


I am writing a validation function in Matlab R2020 to ensure that several arrays meet length requirements before they are processed. The function looks something like

function [arr1, arr2, arr3, arr4] = validate_params_config_format(arr1, arr2, arr3, arr4)
    fprintf("\tParameter configuration format is being validated")
    assert(length(arr1)==length(arr2), "\tValidation failed: unequal length arr1-arr2")
    assert(length(arr3)==length(arr4), "\tValidation failed: unequal length arr3-arr4")
    % other assert statements here
end

If all the assert statements pass, I want to run fprintf("Validation passed").

However, Mathworks documentation only shows how to assertSuccess() for a class, and a Matlab file can only contain one class. I need to have multiple validations for this project, and my colleagues won't appreciate having multiple files to deal with here.

I am an avid Matlab coder, but new to using assert() statements. How can I detect that all the assert statements in a function returned true, without using classes?


Solution

  • assert throws an error when the input is false. So if no error is thrown, all asserts pass.

    If you want to see “all tests pass”, just add a print statement at the bottom of your function:

    
    function [arr1, arr2, arr3, arr4] = validate_params_config_format(arr1, arr2, arr3, arr4)
        disp("\tParameter configuration format is being validated")
        assert(length(arr1)==length(arr2), "\tValidation failed: unequal length arr1-arr2")
        assert(length(arr3)==length(arr4), "\tValidation failed: unequal length arr3-arr4")
        % other assert statements here
    end
        disp("Validation passed")
    

    Note that after one assert fails, and an error is thrown, the remainder of the tests are not performed here. Asserts are really intended to make sure the input to your function is correct, before you do your computations, in the tradition of “fail early”.