arrayfun — Apply a function to each element of array inputs, returning either a numeric array or a cell array.
arrayfun(func, A1, A2, …) evaluates func for every element (or element-wise combination) of the supplied arrays. The builtin mirrors MATLAB's behaviour:
- Inputs must have the same size. Scalars participate by broadcasting their single value.
- The optional
'UniformOutput'name-value flag controls whether results are collected into a numeric/complex/logical/character array (true, the default) or returned as a cell array (false). - When
'ErrorHandler', handleris supplied the handler receives the error struct and the arguments that triggered the failure, letting you supply a fallback result.
How arrayfun works in RunMat
- Accepts function handles, builtin names (character vectors or string scalars), and closures.
- Supports additional scalar parameters:
arrayfun(@(x,c) x + c, A, 5)passes5to every call. - Honors the
'UniformOutput'and'ErrorHandler'name-value pairs for MATLAB-compatible control flow. - Handles numeric, logical, character, and complex arrays. Unsupported types raise a descriptive error instructing you to use
cellfunwhen appropriate. - Empty inputs return empty outputs whose shape matches the first array argument.
- When any input is a
gpuArray, numeric or logical uniform outputs are uploaded back to the GPU so downstream code retains GPU residency. Complex or character uniform outputs remain on the host until providers add the appropriate buffer support. The current implementation computes on the host and therefore inherits the host's floating-point behaviour.
How arrayfun runs on the GPU
When every input is a gpuArray, 'UniformOutput' is true, and the callback resolves to one of the supported builtins (sin, cos, abs, exp, log, sqrt, plus, minus, times, rdivide, or ldivide), RunMat bypasses the host path and dispatches directly to the active provider through the corresponding hooks (unary_* or elem_*). The builtin acts as a fusion barrier—the fusion planner lowers upstream producers before invoking arrayfun because the callback can evaluate arbitrary MATLAB code.
All other combinations—including closures, callbacks with extra scalar parameters, mixed residency, or 'UniformOutput', false—gather inputs to the host, execute the callback element-wise, and then upload numeric or logical uniform results back to the GPU so later code continues with device residency. Complex and character uniform outputs remain host-resident until device representations are available. Cell outputs are always 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 additional scalar parameters
A = [1 2 3];
offset = 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 0FAQ
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 numeric, logical, or complex scalar.
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 functions to explore
These functions work well alongside arrayfun. Each page has runnable examples you can try in the browser.
cellfun, gpuArray, gather, gpuDevice, gpuInfo, pagefun
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how arrayfun works, line by line, in Rust.
- View arrayfun.rs on GitHub
- Learn how the 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 — faster, on any GPU, with no license required.
- Simulations that took hours now take minutes. RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed.
- Start running code in seconds. Open the browser sandbox or download a single binary. No license server, no IT ticket, no setup.
- A full development environment. GPU-accelerated 2D and 3D plotting, automatic versioning on every save, and a browser IDE you can share with a link.