Documentation

cellfun

Apply function to each cell in cell array

Syntax

A = cellfun(func,C)
A = cellfun(func,C1,...,Cn)
A = cellfun(___,南e,Value)
[A1,...,Am] = cellfun(___)

Description

example

A= cellfun(func,C)applies the functionfuncto the contents of each cell of cell arrayC, one cell at a time.cellfunthen concatenates the outputs fromfuncinto the output arrayA, so that for theith element ofC,A(i) = func(C{i}). The input argumentfuncis a function handle to a function that takes one input argument and returns a scalar. The output fromfunccan have any data type, so long as objects of that type can be concatenated. The arrayAand cell arrayChave the same size.

You cannot specify the order in whichcellfuncalculates the elements ofA或者依靠他们在任何特定的顺序.

example

A = cellfun(func,C1,...,Cn)appliesfuncto the contents of the cells ofC1,...,Cn, so thatA(i) = func(C1{i},...,Cn{i}). The functionfuncmust takeninput arguments and return a scalar. The cell arraysC1,...,Cnall must have the same size.

example

A = cellfun(___,Name,Value)appliesfuncwith additional options specified by one or moreName,Valuepair arguments. For example, to return output values in a cell array, specify'UniformOutput',false. You can returnAas a cell array whenfuncreturns values that cannot be concatenated into an array. You can useName,Valuepair arguments with the input arguments of either of the previous syntaxes.

example

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

The number of output arguments fromfuncneed not be the same as the number of input arguments specified byC1,...,Cn.

Examples

collapse all

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

C = {1:10, [2; 4; 6], []}
C =1x3 cell array{1x10 double} {3x1 double} {0x0 double}

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

A = cellfun(@mean,C)
A =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 theplotfunction and use them to add different markers to each set of data points.cellfuncan return arrays of any data type, so long as objects of that data type can be concatenated.

figure holdonp = cellfun (@plot, X, Y);(1页)。标志='o'; p(2).Marker ='+'; p(3).Marker ='s'; holdoff

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

C = {1:10, [2; 4; 6], []}
C =1x3 cell array{1x10 double} {3x1 double} {0x0 double}

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

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

You can usecellfun有趣的应用ctions to cell arrays of character vectors and to string arrays.cellfuntreats 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 array{'Monday'} {'Tuesday'} {'Wednesday'} {'Thursday'} {'Friday'}

Create three-letter abbreviations for the names using thecellfunfunction. 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',falsename-value pair.

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

You also can callcellfunon a string array. For compatibility,cellfuntreats each element of a string array as though it were a character vector. If you specify a function that returns text, thencellfunreturns it as a cell array of character vectors, not as a string array.

Create abbreviations for names in a string array usingcellfun.

str = ["Saturday","Sunday"]
str =1x2 string array"Saturday" "Sunday"
B = cellfun(@(x) x(1:3),str,'UniformOutput',false)
B =1x2 cell array{'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 or a character vector.

funccan 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 specifyfuncas a character vector, rather than a function handle, but only for a limited set of function names.funccan be:'isempty','islogical','isreal','length','ndims','prodofsize','size', or'isclass'.

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

  • cellfundoes not call any overloaded versions of the function.

  • Thesizeandisclassfunctions require additional inputs to thecellfunfunction:

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

    A = cellfun('isclass',C,classname)returns logical1(true) for each element ofCthat matches theclassnameargument. This syntax returns logical 0 (false) for objects that are a subclass ofclassname.

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

Input array, specified as a cell array or a string array. IfCis a string array, thencellfuntreats each element ofCas though it were a character vector, not a string.

Name-Value Pair Arguments

Specify optional comma-separated pairs ofName,Valuearguments.Nameis the argument name andValueis the corresponding value.Namemust appear inside single quotes (' '). You can specify several name and value pair arguments in any order asName1,Value1,...,NameN,ValueN.

Example:= cellfun (@mean C UniformOutput,假)returns the outputs frommeanin a cell array. Use the'UniformOutput',falsename-value pair ifCcontains numeric matrices andmeanreturns vectors.

collapse all

True or false, specified as the comma-separated pair consisting of'UniformOuput'and either1(true) or0(false).

Value of'UniformOutput'

Description

1(true)

funcmust return scalars thatcellfunconcatenates into arrays.

0(false)

cellfunreturns the outputs offuncin cell arrays. The outputs offunccan have any sizes and different data types.

Function to catch errors, specified as the comma-separated pair consisting of'ErrorHandler'and a function handle. Iffuncthrows 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 asfunc. 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 offunc.

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 whichfuncthrew the error

The remaining input arguments to the error handler are the input arguments for the call tofuncthat madefuncthrow the error.

Supposefuncreturns two doubles as output arguments. You can specify the error handler as'ErrorHandler',@errorFunc, whereerrorFuncis 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', thencellfunrethrows the error thrown byfunc.

Output Arguments

collapse all

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

By default,cellfunconcatenates the outputs fromfuncinto an array.funcmust return scalars. Iffuncreturns objects, then the class that the objects belong to must meet these requirements.

  • Support assignment by linear indexing into the object array

  • Have areshapemethod that returns an array that has the same size as the input

If the value of the'UniformOutput'name-value pair argument is0(false), thencellfunreturns outputs in a cell array. In that case, the outputs fromfunccan have any sizes and different data types.

Extended Capabilities

Introduced before R2006a

Was this topic helpful?