Assertions for debugging
MuPAD® notebooks will be removed in a future release. Use MATLAB® live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some differences. For more information, see Convert MuPAD Notebooks to MATLAB Live Scripts.
assert(cond) declares that
cond holds true at the moment when
the statement is evaluated. By default, MuPAD® does not care about
assertions. After setting
however, MuPAD checks every assertion and stops with an error
if boolean evaluation of
cond does not give
Assertions are a major debugging tool for programmers: by stating frequently what they think to have achieved, programmers make it easy for themselves to detect the first unintended intermediate result.
Suppose we want to write a function
takes an integer as its argument and returns 0 if
that integer is a multiple of 3,
and 1 otherwise. One idea
how to code this could be the following: given an integer n, n modulo
3 must be equal to one of - 1, 1,
or 0. In any case,
mod 3) should do what we want:
f := proc(n: DOM_INT): DOM_INT local k: DOM_INT; begin k := n mod 3; assert(k = 1 or k = -1 or k = 0); abs(k) end_proc
Checking assertions is switched on or off using
oldtestargs := testargs(): testargs(FALSE): f(5)
The result does not equal
1. For debugging
purposes, we switch on assertion checking:
Error: Assertion 'k = 1 or k = -1 or k = 0' has failed. [f]
A boolean expression
TRUE or raises an error.