assert — Throw an error when a condition is false, matching MATLAB and RunMat assert semantics.
assert(cond, ...) aborts execution when cond is false (or contains zero/NaN values) and otherwise returns no output. Error identifier handling, message formatting, and argument validation follow MATLAB and RunMat assert semantics.
Syntax
out = assert(condition)
out = assert(condition, message)
out = assert(condition, message, A...)
out = assert(condition, message_id, message)
out = assert(condition, message_id, message, A...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
condition | Any | Yes | — | Logical/numeric condition that must evaluate to true. |
message | StringScalar | Yes | "Assertion failed." | Failure message text. |
message | StringScalar | Yes | "Assertion failed." | Failure message template text. |
A | Any | Variadic | — | Formatting values for the message template. |
message_id | StringScalar | Yes | "RunMat:assertion:failed" | Message identifier. |
Returns
| Name | Type | Description |
|---|---|---|
out | NumericArray | Zero when the assertion passes. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:assertion:failed | Condition evaluates to false and no custom identifier/message override is provided. | Assertion failed. |
RunMat:assertion:invalidCondition | First argument is not a supported logical or numeric condition input. | assert: first input must be logical or numeric. |
RunMat:assertion:invalidInput | Message identifier/message text or formatting payload is invalid. | assert: invalid input argument |
RunMat:minrhs | No condition argument is provided. | Not enough input arguments. |
How assert works
- 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)raisesRunMat: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 toRunMat:*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
RunMat:assertion:invalidInput. - Conditions supplied as gpuArray values are gathered to host memory prior to evaluation so that MATLAB semantics continue to apply.
Does RunMat run assert on the GPU?
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
Checking that all elements are nonzero
A = [1 2 3];
assert(all(A))Verifying array bounds during development
signal = 1:20;
idx = 12;
assert(idx >= 1 && idx <= numel(signal), ...
"Index %d is outside [1, %d].", idx, numel(signal))Attaching a custom identifier for tooling
M = magic(3);
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
samples = [1.0 2.5 3.7 4.2];
avg = mean(samples);
assert(~isnan(avg), "Average must be finite.")Ensuring structure fields exist before use
cfg = struct("timeout", 30, "rate", 60);
assert(isfield(cfg, "rate"), ...
"runmat:config:missingField", ...
"Configuration missing required field '%s'.", "rate")Detecting invalid enumeration values early
mode = "linear";
valid = ["nearest", "linear", "spline"];
assert(any(mode == valid), ...
"Invalid interpolation mode '%s'.", mode)Validating dimensions before expensive work
A = rand(3, 4);
B = rand(4, 5);
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))Using assert with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how assert changes the result.
Run a small assert example, explain the result, then change one input and compare the output.
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 RunMat: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 RunMat: to match MATLAB behaviour.
What happens if my format string is malformed?⌄
The builtin raises RunMat: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.
Related Diagnostics functions
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how assert is executed, line by line, in Rust.
- View the source for assert in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.