assert — Throw a MATLAB-style error when a logical or numeric condition evaluates to false.
assert(cond, ...) aborts execution with a MATLAB-compatible error when cond is false or contains any zero/NaN elements. When the condition is true (or an empty array), execution continues with no output. RunMat mirrors MATLAB’s identifier normalisation, message formatting, and argument validation rules.
How does the assert function behave in MATLAB / RunMat?
- The first argument must be logical or numeric (real or complex). Scalars must evaluate to true; arrays must contain only nonzero, non-NaN elements (complex values fail when both real and imaginary parts are zero or contain NaNs). Empty inputs pass automatically.
assert(cond)raisesMATLAB:assertion:failedwith messageAssertion failed.whencondis false.assert(cond, msg, args...)formatsmsgwithsprintf-compatible conversions using any additional arguments.assert(cond, id, msg, args...)uses a custom message identifier (normalised toMATLAB:*when missing a namespace) and the formatted message text.- Arguments are validated strictly: identifiers and message templates must be string scalars or character vectors, and malformed format strings raise
MATLAB:assertion:invalidInput. - Conditions supplied as gpuArray values are gathered to host memory prior to evaluation so that MATLAB semantics continue to apply.
GPU behavior
assert is a control-flow builtin. RunMat gathers GPU-resident tensors (including logical gpuArrays) to host memory before evaluating the condition. No GPU kernels are launched, and the acceleration provider metadata is marked as a gather-immediately operation so execution always follows the MATLAB-compatible CPU path. Residency metadata is preserved so subsequent statements observe the same values they would have seen without the assertion.
Examples of using assert in MATLAB / RunMat
Checking that all elements are nonzero
A = [1 2 3];
assert(all(A))Verifying array bounds during development
idx = 12;
assert(idx >= 1 && idx <= numel(signal), ...
"Index %d is outside [1, %d].", idx, numel(signal))Attaching a custom identifier for tooling
assert(det(M) ~= 0, "runmat:demo:singularMatrix", ...
"Matrix must be nonsingular (determinant is zero).")Guarding GPU computations without manual gathering
G = gpuArray(rand(1024, 1));
assert(all(G > 0), "All entries must be positive.")Converting NaN checks into assertion failures
avg = mean(samples);
assert(~isnan(avg), "Average must be finite.")Ensuring structure fields exist before use
assert(isfield(cfg, "rate"), ...
"runmat:config:missingField", ...
"Configuration missing required field '%s'.", "rate")Detecting invalid enumeration values early
valid = ["nearest", "linear", "spline"];
assert(any(mode == valid), ...
"Invalid interpolation mode '%s'.", mode)Validating dimensions before expensive work
assert(size(A, 2) == size(B, 1), ...
"runmat:demo:dimensionMismatch", ...
"Inner dimensions must agree (size(A,2)=%d, size(B,1)=%d).", ...
size(A, 2), size(B, 1))FAQ
What types can I pass as the condition?
Logical scalars/arrays and numeric scalars/arrays are accepted. Character arrays, strings, cells, structs, and complex values raise MATLAB:assertion:invalidCondition.
How are NaN values treated?
Any NaN element causes the assertion to fail, matching MATLAB’s requirement that all elements are non-NaN and nonzero.
Do empty arrays pass the assertion?
Yes. Empty logical or numeric arrays are treated as true.
Can I omit the namespace in the message identifier?
Yes. RunMat prefixes unqualified identifiers with MATLAB: to match MATLAB behaviour.
What happens if my format string is malformed?
The builtin raises MATLAB:assertion:invalidInput describing the formatting issue.
Does assert run on the GPU?
No. GPU tensors are gathered automatically and evaluated on the CPU to preserve MATLAB semantics.
Can I use strings for messages and identifiers?
Yes. Both character vectors and string scalars are accepted for identifiers and message templates.
What value does assert return when the condition is true?
Like MATLAB, assert has no meaningful return value. RunMat returns 0.0 internally to satisfy the runtime but nothing is produced in MATLAB code.
How do I disable assertions in production code?
Wrap the condition in an if statement controlled by your own flag; MATLAB (and RunMat) always evaluates assert.
How do I distinguish assertion failures from other errors?
Provide a custom identifier (for example runmat:module:assertFailed) and catch it in a try/catch block.
See also
error, warning, isnan, sprintf
Source & Feedback
- Source code: `crates/runmat-runtime/src/builtins/diagnostics/assert.rs`
- Found a bug? Open an issue with a minimal reproduction.