Apply function to each element of array (2025)

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 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 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

Apply function to each element of array (1)

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

funcFunction 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.

AInput 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 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 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.

UniformOutputTrue 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 the func outputs into arrays. func must return scalars of the same data type, or arrayfun errors with this option.

false (0)

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

ErrorHandlerFunction 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 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

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 when UniformOutput is set to true.

  • 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

Version History

Introduced before R2006a

See Also

structfun | cellfun | spfun | cell2mat | splitapply | varfun | rowfun | groupsummary

Topics

  • Anonymous Functions
  • Create Function Handle

MATLAB-Befehl

Sie haben auf einen Link geklickt, der diesem MATLAB-Befehl entspricht:

 

Führen Sie den Befehl durch Eingabe in das MATLAB-Befehlsfenster aus. Webbrowser unterstützen keine MATLAB-Befehle.

Apply function to each element of array (2)

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)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本 (日本語)
  • 한국 (한국어)

Contact your local office

Apply function to each element of array (2025)

FAQs

How to apply function to every element in array in Python? ›

In Python, the map() function can be used to apply a specific function to each element in a list. The map() function takes in two arguments: a function and an iterable (such as a list).

How to apply a function to each element in an array in JavaScript? ›

The forEach() method of Array instances executes a provided function once for each array element.

How to apply a function to each element of an array matlab? ›

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)) .

How to perform an operation on every element in a list in Python? ›

Another approach that can be used to perform operations on each element in a list is to use the for loop in conjunction with the enumerate() function. The enumerate() function returns an iterator that produces tuples containing the index and value of each element in the list.

How to call a function in an array? ›

Example Explained

Note that when you call the function, you only need to use the name of the array when passing it as an argument myFunction(myNumbers) . However, the full declaration of the array is needed in the function parameter ( int myNumbers[5] ).

How to use forEach loop? ›

The forEach loop is a method in JavaScript that allows you to iterate over an array and perform an operation on each element of the array. It takes a callback function as an argument and applies it to each element of the array. const myArray = [1, 2, 3, 4, 5]; myArray. forEach((element) => { console.

What is bind() in JavaScript? ›

The bind() method of Function instances creates a new function that, when called, calls this function with its this keyword set to the provided value, and a given sequence of arguments preceding any provided when the new function is called.

Which function is used to iterate over all elements in a NumPy array? ›

The iterator object nditer , introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

How to use apply_along_axis? ›

Apply a function to 1-D slices along the given axis. Execute func1d(a, *args, **kwargs) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis. This function should accept 1-D arrays.

How to apply function to all elements in array PHP? ›

The `array_map()` function in PHP is a powerful tool for applying a user-defined function to each element of an array or a set of arrays. It takes a callback function and one or more arrays as its arguments, applies the callback function to each element of the arrays, and returns a new array containing the results.

How do you add to each element in an array in Python? ›

Adding Elements to an Array Using the Array Module

With the array module, you can concatenate, or join, arrays using the + operator and you can add elements to an array using the append() , extend() , and insert() methods.

Which method do you apply to run a function forEach item in an array? ›

The forEach() method calls a function for each element in an array.

How do you apply a function to every element in an array in R? ›

lapply() is a function in R that applies a given function (specified by the FUN argument) to each element of a list or vector. It generates a list where each element represents the outcome of applying the tolower() function to each element within the given vector.

How do you loop through every value in an array in Python? ›

You can use the for in loop to loop through all the elements of an array.

How do you join everything in an array in Python? ›

The join() function in Python is a tool for merging items from a collection into one string. It works by taking a collection like a list or tuple and combining its elements into a string with a separator. This function simplifies the task of creating a string from elements without the need for complex loops or logic.

How do you assign a value to every element in an array? ›

In the C programming language, you can assign values to each element of an array without having to declare it first by using a loop. For example, you could use a for loop to iterate through each element of the array and assign it a value: int array[10]; for (int i = 0; i < 10; i++) {

How do you right shift all elements in an array in Python? ›

Use np. roll(arr, n) to shift the elements of the numpy array arr by n positions to the right.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Roderick King

Last Updated:

Views: 6268

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Roderick King

Birthday: 1997-10-09

Address: 3782 Madge Knoll, East Dudley, MA 63913

Phone: +2521695290067

Job: Customer Sales Coordinator

Hobby: Gunsmithing, Embroidery, Parkour, Kitesurfing, Rock climbing, Sand art, Beekeeping

Introduction: My name is Roderick King, I am a cute, splendid, excited, perfect, gentle, funny, vivacious person who loves writing and wants to share my knowledge and understanding with you.