Apply function to each element of array (2024)

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

Commande MATLAB

Vous avez cliqué sur un lien qui correspond à cette commande MATLAB:

 

Pour exécuter la commande, saisissez-la dans la fenêtre de commande de MATLAB. Les navigateurs web ne supportent pas les commandes MATLAB.

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 (2024)

References

Top Articles
Funeral for a Friend Concert Setlists
Keeper Of The Lost Cities Series - Shannon Messenger
Express Pay Cspire
NYT Mini Crossword today: puzzle answers for Tuesday, September 17 | Digital Trends
Pet For Sale Craigslist
Nwi Police Blotter
Sam's Club Gas Price Hilliard
Computer Repair Tryon North Carolina
Crusader Kings 3 Workshop
Craigslist Jobs Phoenix
อพาร์ทเมนต์ 2 ห้องนอนในเกาะโคเปนเฮเกน
General Info for Parents
Identogo Brunswick Ga
Dump Trucks in Netherlands for sale - used and new - TrucksNL
Hood County Buy Sell And Trade
The ULTIMATE 2023 Sedona Vortex Guide
Paradise leaked: An analysis of offshore data leaks
Convert 2024.33 Usd
Tygodnik Polityka - Polityka.pl
TBM 910 | Turboprop Aircraft - DAHER TBM 960, TBM 910
Craigslist Pinellas County Rentals
How To Level Up Roc Rlcraft
Van Buren County Arrests.org
Ratchet & Clank Future: Tools of Destruction
Fort Mccoy Fire Map
Glenda Mitchell Law Firm: Law Firm Profile
Catherine Christiane Cruz
Terry Bradshaw | Biography, Stats, & Facts
Www.dunkinbaskinrunsonyou.con
Filthy Rich Boys (Rich Boys Of Burberry Prep #1) - C.M. Stunich [PDF] | Online Book Share
Miles City Montana Craigslist
1636 Pokemon Fire Red U Squirrels Download
Craigslist Boerne Tx
*!Good Night (2024) 𝙵ull𝙼ovie Downl𝚘ad Fr𝚎e 1080𝚙, 720𝚙, 480𝚙 H𝙳 HI𝙽DI Dub𝚋ed Fil𝙼yz𝚒lla Isaidub
What are the 7 Types of Communication with Examples
Ofw Pinoy Channel Su
Seymour Johnson AFB | MilitaryINSTALLATIONS
Selfservice Bright Lending
Page 5662 – Christianity Today
Spn-523318
10 Rarest and Most Valuable Milk Glass Pieces: Value Guide
Noaa Duluth Mn
St Vrain Schoology
Elven Steel Ore Sun Haven
Yourcuteelena
Go Nutrients Intestinal Edge Reviews
Ts In Baton Rouge
How to Connect Jabra Earbuds to an iPhone | Decortweaks
Theater X Orange Heights Florida
Free Carnival-themed Google Slides & PowerPoint templates
Hkx File Compatibility Check Skyrim/Sse
Mike De Beer Twitter
Latest Posts
Article information

Author: Frankie Dare

Last Updated:

Views: 6288

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Frankie Dare

Birthday: 2000-01-27

Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

Phone: +3769542039359

Job: Sales Manager

Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.