Apply function to each element of array
collapse all in page
Syntax
B = arrayfun(func,A)
B = arrayfun(func,A1,...,An)
B = arrayfun(___,Name,Value)
[B1,...,Bm] = arrayfun(___)
Description
example
B = arrayfun(func,A)
applies the function func
to the elements of A
, one element at a time. arrayfun
then concatenates the outputs from func
into the output array B
, so that for the i
th element of A
, B(i) = func(A(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 arrays A
and B
have the same size.
You cannot specify the order in which arrayfun
calculates the elements of B
or rely on them being done in any particular order.
B = arrayfun(func,A1,...,An)
applies func
to the elements of the arrays A1,...,An
, so that B(i) = func(A1(i),...,An(i))
. The function func
must take n
input arguments and return a scalar. The arrays A1,...,An
all must have the same size.
example
B = arrayfun(___,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 B
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
[B1,...,Bm] = arrayfun(___)
returns multiple output arrays B1,...,Bm
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 A1,...,An
.
Examples
collapse all
Apply Function to Field of Structure Array
Open Live Script
Create a nonscalar structure array. Each structure has a field that contains a vector of random numbers. The vectors have different sizes.
S(1).f1 = rand(1,5);S(2).f1 = rand(1,10);S(3).f1 = rand(1,15)
S=1×3 struct array with fields: f1
Calculate the mean for each field in S
by using the arrayfun
function. You cannot use structfun
for this calculation because the input argument to structfun
must be a scalar structure.
A = arrayfun(@(x) mean(x.f1),S)
A = 1×3 0.6786 0.6216 0.6069
Return Object Array
Open Live Script
Create a structure array in which each structure has two fields containing numeric arrays.
S(1).X = 5:5:100; S(1).Y = rand(1,20);S(2).X = 10:10:100; S(2).Y = rand(1,10);S(3).X = 20:20:100; S(3).Y = rand(1,5)
S=1×3 struct array with fields: X Y
Plot the numeric 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. arrayfun
can return arrays of any data type so long as objects of that data type can be concatenated.
figurehold onp = arrayfun(@(a) plot(a.X,a.Y),S);p(1).Marker = 'o';p(2).Marker = '+';p(3).Marker = 's';hold off
Return Outputs in Cell Array
Open Live Script
Create a nonscalar structure array. Each structure has a field that contains numeric matrices.
S(1).f1 = rand(3,5);S(2).f1 = rand(6,10);S(3).f1 = rand(4,2)
S=1×3 struct array with fields: f1
Calculate the mean for each field in S
by using the arrayfun
function. mean
returns vectors containing the mean of each column, so the means cannot be returned as an array. To return the means in a cell array, specify the 'UniformOutput',false
name-value pair.
A = arrayfun(@(x) mean(x.f1),S,'UniformOutput',false)
A=1×3 cell array {[0.6158 0.5478 0.5943 0.6977 0.7476]} {[0.6478 0.6664 0.3723 0.4882 0.4337 0.5536 0.5124 0.4436 0.5641 0.5566]} {[0.3534 0.5603]}
Return Multiple Output Arrays
Open Live Script
Create a nonscalar structure array.
S(1).f1 = 1:10;S(2).f1 = [2; 4; 6];S(3).f1 = []
S=1×3 struct array with fields: f1
Calculate the sizes of each field of S
by using the arrayfun
function. The number of rows and columns are each in 1-by-3 numeric arrays.
[nrows,ncols] = arrayfun(@(x) size(x.f1),S)
nrows = 1×3 1 3 0
ncols = 1×3 10 1 0
Input Arguments
collapse all
func
— Function to apply
function handle
Function to apply to the elements of the input arrays, specified as a function handle.
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.
Example: B = arrayfun(@round,A)
returns the integer part of each element of A
.
A
— Input array
array
Input array. A
can be an array that belongs to any of the fundamental data types, except for table
and timetable
, or to any class that supports linear indexing.
To apply a function to the contents of a table or timetable, use the varfun
, rowfun
, splitapply
, or groupsummary
functions.
If you define the class that A
belongs to, and you also overload the subsref
or size
methods of A
, then arrayfun
places these requirements on A
:
The
size
method ofA
must return an array of doubles.A
must support linear indexing.The product of the sizes returned by the
size
method must not exceed the limit ofA
, as defined by linear indexing intoA
.
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 = arrayfun(@(x) mean(x.f1),S,'UniformOutput',false)
returns the means in a cell array. S
is a structure array in which each structure has a field named f1
.
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 arrayfun
rethrows the error thrown by func
.
Output Arguments
collapse all
B
— 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, arrayfun
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 arrayfun
returns outputs in a cell array. In that case, the outputs from func
can have any sizes and different data types.
Limitations
Heterogeneous Arrays
arrayfun
does not support heterogeneous arrays whenUniformOutput
is set totrue
.Difference in Behavior for Input Arrays of Complex Numbers
If the input array
A
is an array of complex numbers, and some of the elements have imaginary parts equal to zero, then callingarrayfun
and indexing into the array can lead to different results. Thearrayfun
function always treats such numbers as complex numbers with imaginary parts equal to zero. However, indexing returns such values as real numbers.To illustrate the difference in behavior, first create an array of complex numbers.
A = zeros(2,1); A(1) = 1; A(2) = 0 + 1i
A = 1.0000 + 0.0000i 0.0000 + 1.0000i
Then create a cell array and assign the elements of
A
to it. When you index intoA(1)
, its value is returned as a real number because its imaginary part is equal to zero. And you can store real and complex values in different cells ofC1
because cell arrays can store data having different types.C1 = cell(2,1); C1{1} = A(1); C1{2} = A(2)
C1 = 2×1 cell array {[ 1]} {[0.0000 + 1.0000i]}
Call
arrayfun
and access the elements ofA
. Assign its values to a cell array. Whenarrayfun
accessesA(1)
, it treats that value as a complex number and assigns it toC2{1}
.C2 = arrayfun(@(x) x, A, 'UniformOutput', false)
C2 = 2×1 cell array {[1.0000 + 0.0000i]} {[0.0000 + 1.0000i]}
Extended Capabilities
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
This function supports tall arrays with these limitations:
The specified function must not rely on
persistent
variables.The
'ErrorHandler'
name-value pairis not supported.With the
'UniformOutput'
name-valuepair set totrue
(default), the outputs from thespecified 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:
Code generation does not support the
'ErrorHandler'
option.Code generation does not support the
'UniformOutput'
option. The input function toarrayfun
must return a scalar or scalars that can be concatenated into an array.Code generation does not support cell array inputs to
func
.To predetermine the output type for
func
, the code generator can callfunc
before processing theaccumarray
input arguments.If the execution of
func
causes side-effects, for instance by modifying a global or persistent variable or printing to output, then the generated code results can differ from MATLAB results.If the input array to
accumarray
is empty, then the code generator can use zero-valued inputs to predetermine output types.func
must not error when its inputs are zero, or the generated code can produce unexpected errors.
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.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Usage notes and limitations:
See arrayfun (Parallel Computing Toolbox).
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
structfun | cellfun | spfun | cell2mat | splitapply | varfun | rowfun | groupsummary
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