assert — Throw an error when a condition is false, matching MATLAB and RunMat assert semantics.
assert(cond, ...) throws when a logical or logically convertible condition is false and has no public output. A real numeric condition is true only when it is nonempty and every element is nonzero; NaN cannot convert to logical. Optional text supplies a formatted message and a qualified error identifier.
Syntax
assert(condition)
assert(condition, message)
assert(condition, message, A...)
assert(condition, message_id, message)
assert(condition, message_id, message, A...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
condition | Any | Yes | — | Logical or logically convertible 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. |
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 logical or convertible to a logical condition. | assert: first input must be logical or convertible to logical. |
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. |
RunMat:assertion:TooManyOutputs | One or more public outputs are requested from assert. | assert: too many output arguments |
How assert works
- The documented condition is logical or convertible to logical. Logical, character, and real numeric conditions pass only when nonempty and every element is nonzero. All eight integer classes are tested directly from authoritative storage. NaN cannot convert to logical, and complex conditions are a mode-gated RunMat extension.
assert(cond)raisesRunMat:assertion:failedwith messageAssertion failed.whencondis false.assert(cond, msg, A...)formatsmsgwithsprintf-compatible conversions. Each documented A is a character vector, string scalar, or numeric scalar; integer scalar values remain exact through decimal, unsigned, hexadecimal, and string formatting.assert(cond, errID, msg, A...)requires colon-separated identifier fields that each begin with a letter and otherwise contain letters, digits, or underscores. AutomaticRunMat:qualification of an unqualified identifier is a mode-gated RunMat extension.- Arguments are validated strictly: identifiers and message templates must be string scalars or character vectors, replacement arrays reject, and malformed format strings raise
RunMat:assertion:invalidInput. - The public gpuArray form executes on the client. Resident conditions and scalar numeric replacements gather through typed storage; no assertion kernel runs on the GPU.
Does RunMat run assert on the GPU?
assert is a control-flow builtin. Public documentation accepts gpuArray input but states that execution does not run on the GPU. RunMat therefore gathers resident logical, real numeric, and scalar formatting values through authoritative typed storage before host evaluation; all eight integer classes remain exact, and no provider assertion kernel is launched.
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 arrays, character arrays, and real numeric arrays are accepted when convertible to a logical condition. Strings, cells, structs, and other unsupported values reject. Complex conditions are available only in RunMat compatibility mode.
How are NaN values treated?⌄
NaN cannot be converted to logical, so a real condition containing NaN raises the invalid-condition diagnostic rather than an ordinary assertion failure.
Do empty arrays pass the assertion?⌄
No. A condition is true only when its result is nonempty and all elements are nonzero, so empty logical, character, or real numeric conditions fail the assertion.
Can I omit the namespace in the message identifier?⌄
Only in RunMat compatibility mode. The documented form requires colon-separated component and mnemonic fields; RunMat mode can prefix an unqualified identifier with RunMat:.
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?⌄
assert has no public output. RunMat uses an internal control-flow sentinel only to complete runtime dispatch.
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.