When to use assert() in Matlab?

assert, exception, matlab

Solution

For the most part, there is no difference between

assert(X,...)

and

if (~X)
    error(...)
end

and your choice between them is a matter of convenience or style.

The distinction between non-production and production code in MATLAB-based projects is often not the same as the distinction in projects based on other languages.

This is partly because, as you say, MATLAB is typically interpreted rather than compiled; although it's possible to produce applications using MATLAB Compiler or the Builder products that, although not strictly "compiled", do not have visible source code and cannot be debugged. For those sort of applications you would need to handle exceptions and errors just as carefully as you would with a compiled language.

It's also partly because "production" often means something different for projects that use MATLAB than it does for projects in other languages; for example, it might mean that the MATLAB code is automatically converted to C for deployment to a car engine controller, or it might mean that some MATLAB code was running a financial forecasting model and writing results to a production database.

There is a special case where `assert` should be used rather than `if..error..end`, which is when you're using MATLAB Coder to generate C code from MATLAB code. MATLAB Coder inspects `assert` statements in MATLAB code to infer properties of the variables it needs to convert to C, and can generate better C code if it can assume facts about variables that you assert (such as array sizes and types).

One last point: for the specific activity you mention, enforcing a function signature, I would use neither method - `inputParser` is typically more robust and consistent (although a bit verbose), but more importantly it encourages you to design the function signature well in the first place.

Problem

Since Matlab is interpreted, typically spend a lot of time at the beginning of the function enforcing the function signature. For example ``` if nargin ~= 2; error('must provide two input args a and b'); end if a < 0||a ~=floor(a); error('input arg1 must be positive non-zero integer'); end if ~isa(b,'cell') ... ``` Is it better to use Matlab's assert() for this instead? If not, when is the appropriate time to use assert() in Matlab? There is a great discussion on using assert in production code here but I am not certain this applies to interpreted code. Likewise, another good discussion here and I agree with @Dan Dyer regarding assert to express belief about the current state. However, looking at a similar discussion for Python here folks say, only use assert for situations that should never happen (like exceptions for exceptional cases) which is a little contradictory w.r.t. the previous references. Maybe this is more a question about the role assert plays in interpreted languages and less about Matlab.

Original source

Related problems