Apply function to each element of array
[B1,...,Bm] = arrayfun(func,A1,...,An)
[B1,...,Bm] = arrayfun(func,A1,...,An,Name,Value)
[
calls
the function specified by function handle B1,...,Bm
] = arrayfun(func
,A1,...,An
)func
and
passes elements from arrays A1,...,An
, where n
is
the number of inputs to function func
. Output arrays B1,...,Bm
,
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 [B1(i),...,Bm(i)] = func(A1(i),...,An(i))
.
The arrayfun
function does not perform the calls
to function func
in a specific order.
[
calls
function B1,...,Bm
] = arrayfun(func
,A1,...,An
,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 |
|
Arrays that contain the If any input
|
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
|
To run the examples in this section, create a nonscalar structure
array with arrays of different sizes in field f1
.
s(1).f1 = rand(3, 6); s(2).f1 = magic(12); s(3).f1 = ones(5, 10);
Count the number of elements in each f1
field.
counts = arrayfun(@(x) numel(x.f1), s)
The syntax @(x)
creates an anonymous function.
This code returns
counts = 18 144 50
Compute the size of each array in the f1
fields.
[nrows, ncols] = arrayfun(@(x) size(x.f1), s)
This code returns
nrows = 3 12 5 ncols = 6 12 10
Compute the mean of each column in the f1
fields
of s
. Because the output is nonscalar, set UniformOutput
to false
.
averages = arrayfun(@(x) mean(x.f1), s, 'UniformOutput', false)
This code returns
averages = [1x6 double] [1x12 double] [1x10 double]
Create additional nonscalar structures t
and u
,
and test for equality between the arrays in fields f1
across
structures s
, t
, and u
.
t = s; t(1).f1(:)=0; u = s; u(2).f1(:)=0; same = arrayfun(@(x,y,z) isequal(x.f1, y.f1, z.f1), s, t, u)
This code returns
same = 0 0 1
cell2mat
| cellfun
| spfun
| splitapply
| structfun