RunMat
GitHub

arrayfun — Apply a function element-wise across array inputs in MATLAB and RunMat.

arrayfun(func, A1, A2, ...) evaluates func for each element (or element-wise tuple) of the supplied arrays. Inputs must share size (with scalar expansion), 'UniformOutput' controls array-versus-cell output, and 'ErrorHandler' provides MATLAB/RunMat-compatible fallback behavior.

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

NameTypeRequiredDefaultDescription
funcAnyYesFunction handle or callable name.
A1AnyYesFirst input array.
AnAnyVariadicAdditional input arrays.
UniformOutputPropertyNameYes"UniformOutput"Name-value key that toggles uniform output collection.
tfAnyYestrueLogical true/false value for UniformOutput.
ErrorHandlerPropertyNameYes"ErrorHandler"Name-value key that provides fallback callback on per-element failures.
handlerAnyYesCallback invoked with error struct and original scalar arguments.
nameValueAnyVariadicName-value option pairs including UniformOutput and ErrorHandler.

Returns

NameTypeDescription
BAnyElement-wise callback result (uniform array or cell array).

Errors

IdentifierWhenMessage
RunMat:arrayfun:InvalidInputInputs, callable forms, or option tails violate arrayfun argument requirements.arrayfun: invalid input arguments
RunMat:arrayfun:UniformOutputOptionUniformOutput option value is not interpretable as logical true/false.arrayfun: UniformOutput must be logical true or false
RunMat:arrayfun:CallbackFailedCallback invocation fails and no ErrorHandler recovers the element.arrayfun: callback execution failed

How arrayfun works

  • Accepts function handles, builtin names (character vectors or string scalars), and closures.
  • Supports additional scalar parameters: arrayfun(@(x,c) x + c, A, 5) passes 5 to 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 cellfun when 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.

Does RunMat run arrayfun 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    36

Passing additional scalar parameters

A = [1 2 3];
offset = 10;
result = arrayfun(@(x, c) x + c, A, offset)

Expected output:

result =
    11    12    13

Returning 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         0

Using 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 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.

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how arrayfun is executed, line by line, in Rust.

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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.