arrayfun — Apply a function element-wise across array inputs in MATLAB and RunMat.
arrayfun(func, A1, A2, ...) evaluates a scalar callback for each element or element-wise tuple. Ordinary host inputs must have the same size; the documented gpuArray overload accepts compatible sizes. UniformOutput controls array-versus-cell collection, and ErrorHandler receives the documented identifier, message, and linear index when a callback fails.
Syntax
B = arrayfun(func, A1, An...)
B = arrayfun(func, A1, An..., "UniformOutput", tf)
B = arrayfun(func, A1, An..., "ErrorHandler", handler)
B = arrayfun(func, A1, An..., nameValue...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
func | Any | Yes | — | Function handle or callable name. |
A1 | Any | Yes | — | First input array. |
An | Any | Variadic | — | Additional input arrays. |
UniformOutput | PropertyName | Yes | "UniformOutput" | Name-value key that toggles uniform output collection. |
tf | Any | Yes | true | Logical true/false value for UniformOutput. |
ErrorHandler | PropertyName | Yes | "ErrorHandler" | Name-value key that provides fallback callback on per-element failures. |
handler | Any | Yes | — | Callback invoked with error struct and original scalar arguments. |
nameValue | Any | Variadic | — | Name-value option pairs including UniformOutput and ErrorHandler. |
Returns
| Name | Type | Description |
|---|---|---|
B | Any | Element-wise callback result (uniform array or cell array). |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:arrayfun:InvalidInput | Inputs, callable forms, or option tails violate arrayfun argument requirements. | arrayfun: invalid input arguments |
RunMat:arrayfun:UniformOutputOption | UniformOutput option value is not interpretable as logical true/false. | arrayfun: UniformOutput must be logical true or false |
RunMat:arrayfun:CallbackFailed | Callback invocation fails and no ErrorHandler recovers the element. | arrayfun: callback execution failed |
RunMat:arrayfun:UniformOutputType | UniformOutput=true callback result is not a supported scalar type. | arrayfun: callback must return scalar values for UniformOutput=true |
RunMat:arrayfun:InternalError | Internal shape/index/materialization/upload path fails. | arrayfun: internal error |
RunMat:UndefinedFunction | External callable identity cannot be resolved in semantic/runtime boundaries. | arrayfun: undefined function |
How arrayfun works
- The documented callable form is a function handle. Character-vector and string-scalar callable names are a mode-gated RunMat extension.
- Host arrays require equal sizes. Host scalar expansion is a mode-gated RunMat extension; gpuArray input follows the documented compatible-size expansion rule.
UniformOutputaccepts logical true/false or double 1/0. Typed-integer controls reject. With uniform output, every callback or error-handler result must be scalar and retain one data type; all eight integer classes, native single, and complex single are collected without widening.- Host
UniformOutputandErrorHandlerimplement the documented single-output control flow. With gpuArray input these options are a mode-gated RunMat extension because the GPU overload exposes scalar uniform outputs only. - The current implementation handles numeric, logical, character, string, and complex arrays. Standard multiple-output callbacks and cell, struct, and user-object inputs remain general callback/container gaps.
- Empty inputs return empty outputs whose shape matches the first array argument.
- When any input is a gpuArray, supported builtin callbacks may dispatch directly; otherwise authoritative typed inputs gather for callback evaluation and numeric or logical uniform outputs are uploaded back to the provider. Complex or character uniform outputs remain on the host.
Does RunMat run arrayfun on the GPU?
When every input is a gpuArray, uniform output is implicit, and the callback resolves to one of the supported builtins (sin, cos, abs, exp, log, sqrt, plus, minus, times, rdivide, or ldivide), RunMat can dispatch directly through provider hooks. The builtin remains a fusion barrier because arbitrary callback code may execute. Other documented GPU forms use compatible-size typed gather fallback and re-upload uniform numeric or logical results, including exact integer classes. GPU options, host scalar expansion, and text callables are separately mode-gated RunMat extensions; complex, character, and cell outputs remain host-resident.
GPU memory and residency
No. RunMat's auto-offload logic moves tensors to the GPU when profitable. If you do call gpuArray, arrayfun keeps the result on the GPU for uniform numeric or logical outputs so later operations can continue without gathering. Non-uniform or complex/character results stay on the host until GPU representations are available.
Examples
Squaring every element of a matrix
A = [1 2 3; 4 5 6];
B = arrayfun(@(x) x.^2, A)Expected output:
B =
1 4 9
16 25 36Passing equal-sized additional arrays
A = [1 2 3];
offset = [10 10 10];
result = arrayfun(@(x, c) x + c, A, offset)Expected output:
result =
11 12 13Returning cells with non-uniform outputs
strings = ["Run" "Matlab" "GPU"];
chars = arrayfun(@(s) sprintf("%d", strlength(s)), strings, 'UniformOutput', false)Expected output:
chars =
1×3 cell array
{'3'} {'6'} {'3'}Handling errors with a custom error handler
vals = [-1 0 1];
handler = @(err, x) err.identifier;
safe = arrayfun(@(x) sqrt(x), vals, 'ErrorHandler', handler, 'UniformOutput', false)Expected output:
safe =
1×3 cell array
{[0+1i]} {[0]} {[1]}Working with gpuArray inputs
G = gpuArray(linspace(0, pi, 5));
S = arrayfun(@sin, G);
H = gather(S)Expected output:
H =
0 0.7071 1.0000 0.7071 0Using arrayfun with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how arrayfun changes the result.
Run a small arrayfun example, explain the result, then change one input and compare the output.
FAQ
Do I have to call gpuArray before using arrayfun?⌄
No. arrayfun participates in the same planner as other builtins, so the runtime migrates data to the GPU when it determines a benefit. Manual gpuArray calls remain useful for MATLAB compatibility or to force residency for custom workflows.
What happens when the callback returns mixed types?⌄
Set 'UniformOutput', false so the builtin returns a cell array. When 'UniformOutput' is true, every callback invocation must return a scalar of the same data type; RunMat rejects heterogeneous results instead of promoting them.
Can arrayfun handle character inputs?⌄
Yes. Each character element is passed to the callback as a single-character char array and the output follows the normal uniform/non-uniform rules.
Does arrayfun short-circuit on errors?⌄
No. The builtin invokes the optional error handler when a callback fails. If no handler is provided the first error aborts the entire call with a MATLAB-compatible identifier/message pair.
How are logical outputs represented on the GPU?⌄
Logical results use 0.0/1.0 buffers on the device. When you gather them RunMat converts the data back into a logical array automatically.
Related Acceleration functions
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how arrayfun is executed, line by line, in Rust.
- View the source for arrayfun 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.