arrayfun - Apply function to each element of array - MATLAB (original) (raw)
Apply function to each element of array
Syntax
Description
[B](#d126e56337) = arrayfun([func](#d126e56068),[A](#d126e56098))
applies the function func
to the elements ofA
, one element at a time. arrayfun
then concatenates the outputs from func
into the output arrayB
, so that for the i
th element ofA
, B(i) = func(A(i))
. The input argumentfunc
is a function handle to a function that 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 theUniformOutput
name-value argument tofalse
. 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](#d126e56337) = arrayfun([func](#d126e56068),A1,...,An)
applies func
to the elements of the arraysA1,...,An
, so that B(i) = func(A1(i),...,An(i))
. The function func
must taken
input arguments and return a scalar. The arraysA1,...,An
all must have the same size.
[B](#d126e56337) = arrayfun(___,[Name,Value](#namevaluepairarguments))
applies func
with additional options specified by one or moreName,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 useName,Value
pair arguments with the input arguments of either of the previous syntaxes.
[B1,...,Bm] = arrayfun(___)
returns multiple output arrays B1,...,Bm
when func
returnsm
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
Apply Function to Field of Structure Array
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
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.
figure hold on p = 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
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
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)
Input Arguments
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
andtimetable
, or to any class that supports linear indexing.
To apply a function to the contents of a table or timetable, use thevarfun
, 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 asName1=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 'UniformOutput' | Description |
---|---|
true (1) | arrayfun concatenates thefunc outputs into arrays.func must return scalars of the same data type, or arrayfun errors with this option. |
false (0) | arrayfun returns the outputs offunc in cell arrays. The outputs offunc can have any sizes and different data types. |
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 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 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
, whereerrorFunc
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
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 fromfunc
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
), thenarrayfun
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 arrayA
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 ofA
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]}
Callarrayfun
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 pair is 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:
- 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.
- If the execution of
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™.
The arrayfun
function supports GPU array input with these 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