assert

Raises an error if a condition is false.

Category: Programming > Functions

Syntax

assert(cond)

Errors with Assertion failed. unless every element of cond is true.

assert(cond, msg, A1, ..., An)

Errors with the message msg, formatted like sprintf, when the condition fails.

Description

assert documents assumptions and stops early when one is broken, which is easier to debug than a wrong result several lines later. A non-scalar condition passes only if all of its elements are true, so assert(all(x > 0)) can be written as assert(x > 0). When the condition is true the call does nothing.

MATLAB also accepts the forms assert(actual, expected) and assert(actual, expected, tol), which compare values, and an identifier before the message.

Input arguments

cond
Logical or numeric array. The check passes when all elements are nonzero.
msg
Error message, with sprintf format fields.
A1, ..., An
Values for the format fields.

Example

A failed check with a formatted message

x = [3 -1 2];
try
    assert(all(x > 0), 'Found %d non-positive values', sum(x <= 0));
catch err
    disp(err.message)
end
assert(true)
Output
Found 1 non-positive values

Notes

MatLivre implements the condition forms only. The comparison forms (actual, expected, tol) are not supported: a second argument is always read as the message. An identifier given before the message is not separated from it, so the error has no identifier.

See also

error validateattributes MException isequal