View all functions

CategoryAcceleration: Gpu
GPUYes

What does the arrayfun function do in MATLAB / RunMat?

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', handler is supplied the handler receives the error struct and the arguments that triggered the failure, letting you supply a fallback result.

How does the arrayfun function behave in MATLAB / RunMat?

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

arrayfun Function GPU Execution Behaviour

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.

Examples of using the arrayfun function in MATLAB / RunMat

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
    {'MATLAB:arrayfun:FunctionError'}    {[0]}    {[1]}

Working with gpuArray inputs

G = gpuArray(linspace(0, pi, 5));
S = arrayfun(@sin, G);
H = gather(S);

Expected output:

S =
  1×5 gpuArray
         0    0.7071    1.0000    0.7071         0
H =
         0    0.7071    1.0000    0.7071         0

GPU residency in RunMat (Do I need gpuArray?)

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.

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.

See Also

cellfun, gpuArray, gather

Source & Feedback