Main Content

cellfun

Apply function to each cell in cell array

Description

example

A = cellfun(func,C) applies the function func to the contents of each cell of cell array C, one cell at a time. cellfun then concatenates the outputs from func into the output array A, so that for the ith element of C, A(i) = func(C{i}). The input argument func is a function handle to a function that takes one input argument and returns a scalar. The output from func can have any data type, so long as objects of that type can be concatenated. The array A and cell array C have the same size.

You cannot specify the order in which cellfun calculates the elements of A or rely on them being done in any particular order.

example

A = cellfun(func,C1,...,Cn) applies func to the contents of the cells of C1,...,Cn, so that A(i) = func(C1{i},...,Cn{i}). The function func must take n input arguments and return a scalar. The cell arrays C1,...,Cn all must have the same size.

example

A = cellfun(___,Name,Value) applies func with additional options specified by one or more Name,Value pair arguments. For example, to return output values in a cell array, specify 'UniformOutput',false. You can return A as a cell array when func returns values that cannot be concatenated into an array. You can use Name,Value pair arguments with the input arguments of either of the previous syntaxes.

example

[A1,...,Am] = cellfun(___) returns multiple output arrays A1,...,Am when func returns m output values. func can return output arguments that have different data types, but the data type of each output must be the same each time func is called. You can use this syntax with any of the input arguments of the previous syntaxes.

The number of output arguments from func need not be the same as the number of input arguments specified by C1,...,Cn.

Examples

collapse all

Create a cell array that contains numeric arrays of different sizes.

C = {1:10, [2; 4; 6], []}
C=1×3 cell array
    {[1 2 3 4 5 6 7 8 9 10]}    {3x1 double}    {0x0 double}

Calculate the mean of each numeric array, and return the means in an array.

A = cellfun(@mean,C)
A = 1×3

    5.5000    4.0000       NaN

Create two cell arrays that contain numeric arrays of different sizes.

X = {5:5:100, 10:10:100, 20:20:100};
Y = {rand(1,20), rand(1,10), rand(1,5)};

Plot the arrays. Return an array of chart line objects from the plot function and use them to add different markers to each set of data points. cellfun can return arrays of any data type, so long as objects of that data type can be concatenated.

figure
hold on
p = cellfun(@plot,X,Y);
p(1).Marker = 'o';
p(2).Marker = '+';
p(3).Marker = 's';
hold off

Figure contains an axes object. The axes object contains 3 objects of type line.

Create a cell array that contains numeric arrays of different sizes.

C = {1:10, [2; 4; 6], []}
C=1×3 cell array
    {[1 2 3 4 5 6 7 8 9 10]}    {3x1 double}    {0x0 double}

Calculate the sizes of each array in C. The number of rows and columns are each in 1-by-3 numeric arrays.

[nrows,ncols] = cellfun(@size,C)
nrows = 1×3

     1     3     0

ncols = 1×3

    10     1     0

You can use cellfun to apply functions to cell arrays of character vectors and to string arrays. cellfun treats the two kinds of arrays identically.

Create a cell array of character vectors that contains weekday names.

C = {'Monday','Tuesday','Wednesday','Thursday','Friday'}
C = 1x5 cell
    {'Monday'}    {'Tuesday'}    {'Wednesday'}    {'Thursday'}    {'Friday'}

Create three-letter abbreviations for the names using the cellfun function. Specify a function that extracts the first three characters and returns them as a character vector. To return the abbreviations in a cell array, specify the 'UniformOutput',false name-value pair.

A = cellfun(@(x) x(1:3),C,'UniformOutput',false)
A = 1x5 cell
    {'Mon'}    {'Tue'}    {'Wed'}    {'Thu'}    {'Fri'}

You also can call cellfun on a string array. For compatibility, cellfun treats each element of a string array as though it were a character vector. If you specify a function that returns text, then cellfun returns it as a cell array of character vectors, not as a string array.

Create abbreviations for names in a string array using cellfun.

str = ["Saturday","Sunday"]
str = 1x2 string
    "Saturday"    "Sunday"

B = cellfun(@(x) x(1:3),str,'UniformOutput',false)
B = 1x2 cell
    {'Sat'}    {'Sun'}

Input Arguments

collapse all

Function to apply to the contents of the cells of the input cell arrays, specified as a function handle, character vector, or string scalar.

func can correspond to more than one function file and therefore can represent a set of overloaded functions. In these cases, MATLAB® determines which function to call based on the class of the input arguments.

Backward Compatibility

You can specify func as a character vector or string scalar, rather than a function handle, but only for a limited set of function names. func can be: 'isempty', 'islogical', 'isreal', 'length', 'ndims', 'prodofsize', 'size', or 'isclass'.

If you specify a function name rather than a function handle:

  • cellfun does not call any overloaded versions of the function.

  • The size and isclass functions require additional inputs to the cellfun function:

    A = cellfun('size',C,k) returns the size along the kth dimension of each element of C.

    A = cellfun('isclass',C,classname) returns logical 1 (true) for each element of C that matches the classname argument. This syntax returns logical 0 (false) for objects that are a subclass of classname.

Example: A = cellfun(@mean,C) returns the means of the elements of C.

Input array, specified as a cell array or a string array. If C is a string array, then cellfun treats each element of C as though it were a character vector, not a string.

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: A = cellfun(@mean,C,'UniformOutput',false) returns the outputs from mean in a cell array. Use the 'UniformOutput',false name-value pair if C contains numeric matrices and mean returns vectors.

True or false, specified as the comma-separated pair consisting of 'UniformOutput' and either true (1) or false (0).

Value of 'UniformOutput'

Description

true (1)

func must return scalars that cellfun concatenates into arrays.

false (0)

cellfun returns the outputs of func in cell arrays. The outputs of func can have any sizes and different data types.

Function to catch errors, specified as the comma-separated pair consisting of 'ErrorHandler' and a function handle. If func throws an error, then the error handler specified by 'ErrorHandler' catches the error and takes the action specified in the function. The error handler either must throw an error or return the same number of outputs as func. If the value of 'UniformOutput' is true, then the output arguments of the error handler must be scalars and have the same data type as the outputs of func.

The first input argument of the error handler is a structure with these fields:

  • identifier — Error identifier

  • message — Error message text

  • index — Linear index into the input arrays at which func threw the error

The remaining input arguments to the error handler are the input arguments for the call to func that made func throw the error.

Suppose func returns two doubles as output arguments. You can specify the error handler as 'ErrorHandler',@errorFunc, where errorFunc is a function that raises a warning and returns two output arguments.

function [A,B] = errorFunc(S,varargin)
    warning(S.identifier, S.message); 
    A = NaN; 
    B = NaN;
end

If you do not specify 'ErrorHandler', then cellfun rethrows the error thrown by func.

Output Arguments

collapse all

Output array, returned as an array of any data type or as a cell array.

By default, cellfun concatenates the outputs from func into an array. func must return scalars. If func returns objects, then the class that the objects belong to must meet these requirements.

  • Support assignment by linear indexing into the object array

  • Have a reshape method that returns an array that has the same size as the input

If the value of the 'UniformOutput' name-value pair argument is false (0), then cellfun returns outputs in a cell array. In that case, the outputs from func can have any sizes and different data types.

Extended Capabilities

Version History

Introduced before R2006a