Apply function to each cell in cell array
[A1,...,Am] = cellfun(func,C1,...,Cn)
[A1,...,Am] = cellfun(func,C1,...,Cn,Name,Value)
[
calls
the function specified by function handle A1,...,Am
] = cellfun(func
,C1,...,Cn
)func
and
passes elements from cell arrays C1,...,Cn
, where n
is
the number of inputs to function func
. Output arrays A1,...,Am
,
where m
is the number of outputs from function func
,
contain the combined outputs from the function calls. The i
th
iteration corresponds to the syntax [A1(i),...,Am(i)] = func(C1{i},...,Cn{i})
.
The cellfun
function does not perform the calls
to function func
in a specific order.
[
calls
function A1,...,Am
] = cellfun(func
,C1,...,Cn
,Name,Value
)func
with additional options specified
by one or more Name,Value
pair arguments. Possible
values for Name
are 'UniformOutput'
or 'ErrorHandler'
.
| Handle to a function that accepts If function |
|
Cell arrays that contain the |
Specify optional comma-separated pairs of Name,Value
arguments.
Name
is the argument
name and Value
is the corresponding
value. Name
must appear
inside single quotes (' '
).
You can specify several name and value pair
arguments in any order as Name1,Value1,...,NameN,ValueN
.
|
Logical value, as follows:
Default: | ||||||
|
Handle to a function that catches any errors that occur when MATLAB attempts
to execute function MATLAB calls the specified error-handling function with two input arguments:
|
|
Arrays that collect the Function
|
Compute the mean of each vector in cell array C
.
C = {1:10, [2; 4; 6], []}; averages = cellfun(@mean, C)
This code returns
averages = 5.5000 4.0000 NaN
Compute the size of each array in C
, created
in the previous example.
[nrows, ncols] = cellfun(@size, C)
This code returns
nrows = 1 3 0 ncols = 10 1 0
Create a cell array that contains character vectors, and abbreviate
each of them to their first three characters. Because the output character
vectors are nonscalar, set UniformOutput
to false
.
days = {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'}; abbrev = cellfun(@(x) x(1:3), days, 'UniformOutput', false)
The syntax @(x)
creates an anonymous function.
This code returns
abbrev = 'Mon' 'Tue' 'Wed' 'Thu' 'Fri'
Compute the covariance between arrays in two cell arrays C
and D
.
Because the covariance output is nonscalar, set UniformOutput
to false
.
c1 = rand(5,1); c2 = rand(10,1); c3 = rand(15,1); d1 = rand(5,1); d2 = rand(10,1); d3 = rand(15,1); C = {c1, c2, c3}; D = {d1, d2, d3}; covCD = cellfun(@cov, C, D, 'UniformOutput', false)
This code returns
covCD = [2x2 double] [2x2 double] [2x2 double]
Define and call a custom error handling function.
function result = errorfun(S, varargin) warning(S.identifier, S.message); result = NaN; end A = {rand(3)}; B = {rand(5)}; AgtB = cellfun(@(x,y) x > y, A, B, 'ErrorHandler', @errorfun, ... 'UniformOutput', false)
arrayfun
| cell2mat
| spfun
| splitapply
| structfun