Search code examples
matlabsimulink

How do I find which assertion failed in matlab scripts used by simulink model?


I call some matlab scripts from a simulink model, these use assert(). When an assertion fails, simulink gives me a completely useless assertion, without any details about which sub-system or script the assertion occurred in, let alone the line number:

An error occurred while running the simulation and the simulation was terminated
Caused by:
An error occurred during simulation of Model block '<blah>/Model'.
Assertion failed.

However, this is just a model block, it contains many sub-systems and script blocks and stuff.

Any hints on how to find which of my many assertions was triggered?

Not sure it matters, but all of these scripts use the %#codegen tag.


Solution

  • assert() supports custom error messages:

    assert(cond,msg) throws an error and displays the error message, msg, if cond is false.

    assert(cond,msg,A1,...,An) displays an error message that contains formatting conversion characters, such as those used with the MATLAB® sprintf function, if cond is false. Each conversion character in msg is converted to one of the values A1,...,An.

    assert(cond,msgID,msg) throws an error, displays the error message, msg, and includes an error identifier on the exception, if cond is false. The identifier enables you to distinguish errors and to control what happens when MATLAB encounters the errors.

    assert(cond,msgID,msg,A1,...,An) includes an error identifier on the exception and displays a formatted error message.

    Since you have access to the scripts being run, you can update them to include verbose error messages.

    For example:

    >> assert((2+2) == 5)
    Assertion failed.
    

    vs.

    >> assert((2+2) == 5, 'The rules of The Universe still hold')
    Some rules of The Universe still hold