What does the assert function do in MATLAB / RunMat?
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.
assert Function GPU Execution Behaviour
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 the assert function in MATLAB / RunMat
Checking that all elements are nonzero
A = [1 2 3];
assert(all(A));
This runs without output because every element of A is nonzero.
Verifying array bounds during development
idx = 12;
assert(idx >= 1 && idx <= numel(signal), ...
"Index %d is outside [1, %d].", idx, numel(signal));
If idx falls outside the valid range, RunMat throws MATLAB:assertion:failed with the formatted bounds message.
Attaching a custom identifier for tooling
assert(det(M) ~= 0, "runmat:demo:singularMatrix", ...
"Matrix must be nonsingular (determinant is zero).");
When the matrix is singular, the assertion fails with identifier runmat:demo:singularMatrix, allowing downstream tooling to catch it precisely.
Guarding GPU computations without manual gathering
G = gpuArray(rand(1024, 1));
assert(all(G > 0), "All entries must be positive.");
The gpuArray is gathered automatically before evaluation; no manual gather call is required.
Converting NaN checks into assertion failures
avg = mean(samples);
assert(~isnan(avg), "Average must be finite.");
If avg evaluates to NaN, RunMat raises an error so the calling code cannot continue with invalid state.
Ensuring structure fields exist before use
assert(isfield(cfg, "rate"), ...
"runmat:config:missingField", ...
"Configuration missing required field '%s'.", "rate");
Missing fields trigger runmat:config:missingField, making it easy to spot configuration mistakes early.
Detecting invalid enumeration values early
valid = ["nearest", "linear", "spline"];
assert(any(mode == valid), ...
"Invalid interpolation mode '%s'.", mode);
Passing an unsupported option raises a descriptive error so callers can correct the mode value.
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));
If the dimensions disagree, the assertion stops execution before any costly matrix multiplication is attempted.
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
NaNelement 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:invalidInputdescribing the formatting issue. - Does
assertrun 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
assertreturn when the condition is true? Like MATLAB,asserthas no meaningful return value. RunMat returns0.0internally to satisfy the runtime but nothing is produced in MATLAB code. - How do I disable assertions in production code? Wrap the condition in an
ifstatement controlled by your own flag; MATLAB (and RunMat) always evaluatesassert. - How do I distinguish assertion failures from other errors? Provide a custom identifier (for example
runmat:module:assertFailed) and catch it in atry/catchblock.
See Also
error, warning, isnan, sprintf
Source & Feedback
- Full source:
crates/runmat-runtime/src/builtins/diagnostics/assert.rs - Report issues: https://github.com/runmat-org/runmat/issues/new/choose