cellfun

Applies a function to the contents of each cell of a cell array.

Category: Language Fundamentals > Data Types

Syntax

A = cellfun(func, C)

Calls func on each cell and collects scalar results in an array.

A = cellfun(func, C1, C2, ...)

Passes the contents of matching cells of several arrays to func.

[A, B, ...] = cellfun(___)

Collects several outputs of func.

B = cellfun(___, 'UniformOutput', false)

Returns a cell array, so results of any size or class are allowed.

Description

cellfun is the cell array counterpart of a loop over C{k}. With uniform output the scalars are joined into a numeric, logical or char array; if one result is not a scalar, or the classes differ, an error says to set 'UniformOutput' to false.

It is typically used with an anonymous function, as in cellfun(@(s) numel(s), names) to get the length of each name.

Input arguments

func
Function handle, or a legacy name such as 'isempty', 'length' or 'numel'.
C
Cell array. Several cell arrays must have the same size.
'UniformOutput'
Logical. With true (default) each result must be a scalar; with false results are stored in cells.

Output arguments

A
Array with the size of C (uniform output) or a cell array of that size.

Example

Counting and transforming

names = {'ab','c',''};
cellfun(@numel, names)
cellfun(@(x) upper(x), {'a','b'}, 'UniformOutput', false)
[mx, ix] = cellfun(@max, {[1 5 2], [7 3]})
Output
ans = 1×3

     2     1     0
ans = 1×2 cell

    {'A'}    {'B'}
mx = 1×2

     5     7
ix = 1×2

     2     1

See also

arrayfun cell2mat structfun cell isempty