Apply function to each cell in cell array
collapse all in page
Syntax
A = cellfun(func,C)
A = cellfun(func,C1,...,Cn)
A = cellfun(___,Name,Value)
[A1,...,Am] = cellfun(___)
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 i
th 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
must always be the same data type to use this syntax. If the function outputs have different data types, you must set the UniformOuput
name-value argument to false
. 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
Apply Function to Contents of Cell Array
Open Live Script
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
Return Object Array
Open Live Script
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.
figurehold onp = cellfun(@plot,X,Y);p(1).Marker = 'o';p(2).Marker = '+';p(3).Marker = 's';hold off
Return Multiple Output Arrays
Open Live Script
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
Apply Function to Characters in Cell or String Array
Open Live Script
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
func
— Function to apply
function handle | character vector | string scalar
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: 'isempty'
, 'islogical'
, 'isreal'
, 'length'
, 'ndims'
, 'prodofsize'
, 'size'
, or 'isclass'
. However, specifying these functions as character vectors or strings does not work with all data types. For example, if your cell array contains strings or tables, you must use a function handle.
If you specify a function name rather than a function handle:
cellfun
does not call any overloaded versions of the function.The
size
andisclass
functions require additional inputs to thecellfun
function:A = cellfun('size',C,k)
returns the size along thek
th dimension of each element ofC
.A = cellfun('isclass',C,classname)
returns logical1
(true
) for each element ofC
that matches theclassname
argument. This syntax returns logical 0 (false
) for objects that are a subclass ofclassname
.
Example: A = cellfun(@mean,C)
returns the means of the elements of C
.
C
— Input array
cell array | string array
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.
UniformOutput
— True or false
true
(default) | false
True or false, specified as the comma-separated pair consisting of 'UniformOutput'
and either true
(1
) or false
(0
).
Value of | Description |
---|---|
|
|
|
|
ErrorHandler
— Function to catch errors
function handle
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 identifiermessage
— Error message textindex
— Linear index into the input arrays at whichfunc
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
A
— Output array
array of any data type | cell array
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
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
This function supports tall arrays with these limitations:
The input function must be a function handle.
The input function must not rely on
persistent
variables.The
'ErrorHandler'
name-value pairis not supported.With the
'UniformOutput'
name-value pair set totrue
(default), the outputs from the specified function must be numeric, logical, characters, or cell arrays.
For more information, see Tall Arrays for Out-of-Memory Data.
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
cellfun
does not support the use of theErrorHandler
name-value pair.cellfun
does not support signatures where the first inputfunc
is specified as a character vector.cellfun
does not accept strings as input.When using
cellfun
with function handles that require compile-time constants, hard-code the constant parameter within the function handle. For example, to use thesum
function, which requires a compile-time constant for the second argumentdimension
, useout = cellfun(@(x) sum(x, 2), xIn)
. Here, 2 is the hard-coded compile-time constant representing the dimension.
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Distributed Arrays
Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.
This function fully supports distributed arrays. For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).
Version History
Introduced before R2006a
See Also
arrayfun | spfun | cell2mat | structfun | splitapply
Topics
- Anonymous Functions
- Create Function Handle
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- Deutsch
- English
- Français
- United Kingdom (English)
Contact your local office