cellfun — Apply a function to values stored in equal-sized cell arrays.
cellfun invokes a callback for each cell position and collects either a uniform array or a cell array of individual results.
Syntax
[Y1, Y2, ...] = cellfun(func, C...)
Y = cellfun(func, C)
Y = cellfun(func, C1, C2, ...)
Y = cellfun(func, C..., "UniformOutput", tf)
Y = cellfun(func, C..., "ErrorHandler", errfunc)
Y = cellfun(func, C..., "UniformOutput", tf, "ErrorHandler", errfunc)Inputs
func- Type
Any- Required
- Yes
- Description
- Function handle, function name, or supported cellfun shorthand.
C- Type
Any- Required
- Variadic
- Description
- One or more equal-sized cell arrays, followed by constant callback arguments.
UniformOutput- Type
StringScalar- Required
- Yes
- Default
"UniformOutput"- Description
- Name-value key selecting uniform result collection.
tf- Type
Any- Required
- Yes
- Default
true- Description
- Logical scalar, or legacy double zero or one.
ErrorHandler- Type
StringScalar- Required
- Yes
- Default
"ErrorHandler"- Description
- Name-value key selecting a callback error handler.
errfunc- Type
Any- Required
- Yes
- Description
- Error-handler function handle or name.
Returns
Y- Type
Any- Description
- One mapped collection for each requested callback output.
Returned values from cellfun depend on how many outputs the caller requests.
Errors
RunMat:cellfun:InvalidInput- When
- Input callback, cell-array arguments, or name-value forms are invalid.
- Message
cellfun: invalid input arguments
RunMat:cellfun:UniformOutput- When
- UniformOutput requirements are violated.
- Message
cellfun: uniform output contract violated
RunMat:cellfun:FunctionError- When
- The mapped callback or ErrorHandler cannot complete.
- Message
cellfun: callback execution error
Cell-wise callback execution
Y = cellfun(func,C1,C2,...) calls func once per cell position, passing the contents of each input cell. All cell-array inputs must have the same shape. Once a non-cell argument appears, it and the remaining non-cell arguments are constants passed to every invocation.
Function handles, anonymous and captured functions, and ordinary function names use RunMat's normal callable-resolution rules. The documented shorthand names isempty, islogical, isreal, length, ndims, prodofsize, size, and isclass are accepted without an @ prefix.
Output and error handling
UniformOutput defaults to true. Each requested callback output must be a scalar compatible with its collected result class. Multiple requested outputs are collected independently; with zero requested outputs, callbacks still run for their effects. Set 'UniformOutput', false when callbacks return arrays, strings, structures, resident values, or heterogeneous values; the outer result is then a cell array with the input shape.
ErrorHandler receives a structure with identifier, message, index, and indices, followed by the cell contents and constant arguments for the failed position. Its return value is collected in place of the failed callback result.
Fixed-width integer results retain one exact common class. Logical and double results may promote according to the uniform collection contract, and real results may promote to a matching complex representation. Each requested output is collected independently. Discarding all outputs still invokes each callback with zero requested outputs, preserving its effects. Error handlers receive the same requested count.
Provider-resident values
cellfun is host-controlled. Provider-resident values stored inside input cells or passed as constants are gathered through their owning provider before callback invocation. Uniform packed output is host-resident.
With 'UniformOutput', false, callback results are inserted into the result cell without an automatic gather, so a returned provider-resident value keeps its residency. Callback execution makes cellfun a fusion boundary.
Examples
Collect values and indices from each callback
C = {[4 1], [2 7]};
[peaks, indices] = cellfun(@max, C);Expected output:
peaks = [4 7], indices = [1 2]Measure text stored in cells
C = {'apple', 'banana', 'cherry'};
lengths = cellfun(@length, C)Expected output:
lengths = [5 6 6]Map equal-sized cell arrays together
A = {1, 2, 3};
B = {4, 5, 6};
totals = cellfun(@plus, A, B)Expected output:
totals = [5 7 9]Keep non-scalar results in cells
names = {'Ada', 'Linus', 'Katherine'};
upper_names = cellfun(@upper, names, 'UniformOutput', false)Expected output:
upper_names is a 1-by-3 cell arrayPass a constant argument to every callback
C = {magic(3), eye(3)};
rows = cellfun('size', C, 1)Expected output:
rows = [3 3]Use a supported shorthand function name
C = {[], 1:5, zeros(0, 3)};
flags = cellfun('isempty', C)Expected output:
flags = logical [1 0 1]Replace callback failures with indexed defaults
C = {1, 2, 3};
handler = @(err, value) err.index;
values = cellfun(@(value) value(2), C, 'ErrorHandler', handler)Expected output:
values = [1 2 3]Collect exact fixed-width integer results
base = uint64(2^53);
C = {base + uint64(1), base + uint64(3)};
values = cellfun(@(x) x + uint64(1), C)Expected output:
values retains exact uint64 storage above flintmaxUsing cellfun with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how cellfun changes the result.
Run a small cellfun example, explain the result, then change one input and compare the output.
FAQ
Does cellfun modify its input cells?⌄
No. It reads each cell value and creates a new result.
Can callbacks return strings or structures?⌄
Yes with 'UniformOutput', false, which retains each result in a cell.
Do constant arguments need the cell-array shape?⌄
No. Non-cell arguments following the cell inputs are passed unchanged to every callback invocation.
What happens for empty inputs?⌄
The result keeps the empty input shape. Nonuniform mode returns an empty cell array, and uniform mode returns an empty double array.
How does cellfun differ from arrayfun?⌄
cellfun passes each cell's stored value to the callback. arrayfun extracts scalar elements from numeric, logical, character, string, or complex arrays.
Can callbacks capture variables?⌄
Yes. Anonymous functions and other closures retain their captured values and receive each cell's contents after those captures.
Which names can omit the function-handle prefix?⌄
The documented shorthand set is isempty, islogical, isreal, length, ndims, prodofsize, size, and isclass. Ordinary named callbacks also follow the session's callable-resolution rules.
When is a loop clearer?⌄
Use a loop when the body has several steps, mutates surrounding state, or needs custom control flow. Use cellfun for a compact cell-wise callback with a regular collection contract.
Related Cells functions
Source you can read
Every RunMat function's source is public. Read exactly how cellfun is executed, line by line, in Rust.
- View the source for cellfun in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/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.