Main Content

arrayfun

Apply function to each element of array

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 ith 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 can have any data type, so long as objects of that type can be concatenated. 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

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

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

Figure contains an axes object. The axes object contains 3 objects of type line.

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.6478 0.6664 ... ]}    {[0.3534 0.5603]}

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

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.

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 of A 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 of A, as defined by linear indexing into A.

Name-Value Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

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.

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)

func must return scalars that arrayfun concatenates into arrays.

false (0)

arrayfun returns the outputs of func in cell arrays. The outputs of func can have any sizes and different data types.

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 identifier

  • message — Error message text

  • index — Linear index into the input arrays at which func 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

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

  • 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 calling arrayfun and indexing into the array can lead to different results. The arrayfun 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 into A(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 of C1 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 of A. Assign its values to a cell array. When arrayfun accesses A(1), it treats that value as a complex number and assigns it to C2{1}.

    C2 = arrayfun(@(x) x, A, 'UniformOutput', false)
    
    C2 =
    
      2×1 cell array
    
        {[1.0000 + 0.0000i]}
        {[0.0000 + 1.0000i]}
    

Extended Capabilities

Introduced before R2006a