Apply function to each cell in cell array (2024)

Apply function to each cell in cell array

collapse all in page

Syntax

A = cellfun(func,C)

A = cellfun(func,C1,...,Cn)

A = cellfun(___,Name,Value)

[A1,...,Am] = cellfun(___)

Description

example

A = cellfun(func,C) applies the function func to the contents of each cell of cell array C, one cell at a time. cellfun then concatenates the outputs from func into the output array A, so that for the ith element of C, A(i) = func(C{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 array A and cell array C have the same size.

You cannot specify the order in which cellfun calculates the elements of A or rely on them being done in any particular order.

example

A = cellfun(func,C1,...,Cn) applies func to the contents of the cells of C1,...,Cn, so that A(i) = func(C1{i},...,Cn{i}). The function func must take n input arguments and return a scalar. The cell arrays C1,...,Cn all must have the same size.

example

A = cellfun(___,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 A 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

[A1,...,Am] = cellfun(___) returns multiple output arrays A1,...,Am 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 C1,...,Cn.

Examples

collapse all

Apply Function to Contents of Cell Array

Open Live Script

Create a cell array that contains numeric arrays of different sizes.

C = {1:10, [2; 4; 6], []}
C=1×3 cell array {[1 2 3 4 5 6 7 8 9 10]} {3x1 double} {0x0 double}

Calculate the mean of each numeric array, and return the means in an array.

A = cellfun(@mean,C)
A = 1×3 5.5000 4.0000 NaN

Return Object Array

Create two cell arrays that contain numeric arrays of different sizes.

X = {5:5:100, 10:10:100, 20:20:100};Y = {rand(1,20), rand(1,10), rand(1,5)};

Plot the 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. cellfun can return arrays of any data type, so long as objects of that data type can be concatenated.

figurehold onp = cellfun(@plot,X,Y);p(1).Marker = 'o';p(2).Marker = '+';p(3).Marker = 's';hold off

Apply function to each cell in cell array (1)

Return Multiple Output Arrays

Open Live Script

Create a cell array that contains numeric arrays of different sizes.

C = {1:10, [2; 4; 6], []}
C=1×3 cell array {[1 2 3 4 5 6 7 8 9 10]} {3x1 double} {0x0 double}

Calculate the sizes of each array in C. The number of rows and columns are each in 1-by-3 numeric arrays.

[nrows,ncols] = cellfun(@size,C)
nrows = 1×3 1 3 0
ncols = 1×3 10 1 0

Apply Function to Characters in Cell or String Array

Open Live Script

You can use cellfun to apply functions to cell arrays of character vectors and to string arrays. cellfun treats the two kinds of arrays identically.

Create a cell array of character vectors that contains weekday names.

C = {'Monday','Tuesday','Wednesday','Thursday','Friday'}
C = 1x5 cell {'Monday'} {'Tuesday'} {'Wednesday'} {'Thursday'} {'Friday'}

Create three-letter abbreviations for the names using the cellfun function. Specify a function that extracts the first three characters and returns them as a character vector. To return the abbreviations in a cell array, specify the 'UniformOutput',false name-value pair.

A = cellfun(@(x) x(1:3),C,'UniformOutput',false)
A = 1x5 cell {'Mon'} {'Tue'} {'Wed'} {'Thu'} {'Fri'}

You also can call cellfun on a string array. For compatibility, cellfun treats each element of a string array as though it were a character vector. If you specify a function that returns text, then cellfun returns it as a cell array of character vectors, not as a string array.

Create abbreviations for names in a string array using cellfun.

str = ["Saturday","Sunday"]
str = 1x2 string "Saturday" "Sunday"
B = cellfun(@(x) x(1:3),str,'UniformOutput',false)
B = 1x2 cell {'Sat'} {'Sun'}

Input Arguments

collapse all

funcFunction to apply
function handle | character vector | string scalar

Function to apply to the contents of the cells of the input cell arrays, specified as a function handle, character vector, or string scalar.

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.

Backward Compatibility

You can specify func as a character vector or string scalar, rather than a function handle, but only for a limited set of function names: 'isempty', 'islogical', 'isreal', 'length', 'ndims', 'prodofsize', 'size', or 'isclass'. However, specifying these functions as character vectors or strings does not work with all data types. For example, if your cell array contains strings or tables, you must use a function handle.

If you specify a function name rather than a function handle:

  • cellfun does not call any overloaded versions of the function.

  • The size and isclass functions require additional inputs to the cellfun function:

    A = cellfun('size',C,k) returns the size along the kth dimension of each element of C.

    A = cellfun('isclass',C,classname) returns logical 1 (true) for each element of C that matches the classname argument. This syntax returns logical 0 (false) for objects that are a subclass of classname.

Example: A = cellfun(@mean,C) returns the means of the elements of C.

CInput array
cell array | string array

Input array, specified as a cell array or a string array. If C is a string array, then cellfun treats each element of C as though it were a character vector, not a string.

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 = cellfun(@mean,C,'UniformOutput',false) returns the outputs from mean in a cell array. Use the 'UniformOutput',false name-value pair if C contains numeric matrices and mean returns vectors.

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)

cellfun concatenates the func outputs into arrays. func must return scalars of the same data type, or cellfun errors with this option.

false (0)

cellfun 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 cellfun rethrows the error thrown by func.

Output Arguments

collapse all

A — 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, cellfun 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 cellfun returns outputs in a cell array. In that case, the outputs from func can have any sizes and different data types.

Extended Capabilities

Version History

Introduced before R2006a

See Also

arrayfun | spfun | cell2mat | structfun | splitapply

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.

Apply function to each cell in cell 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 cell in cell array (2024)

References

Top Articles
GTA Online guide with everything you need for your criminal empire
GTA Online: G's Cache Locations: Explained - GadgetMates
Use Copilot in Microsoft Teams meetings
Faridpur Govt. Girls' High School, Faridpur Test Examination—2023; English : Paper II
Monthly Forecast Accuweather
Kokichi's Day At The Zoo
Team 1 Elite Club Invite
CKS is only available in the UK | NICE
Mlifeinsider Okta
Sitcoms Online Message Board
Delectable Birthday Dyes
Walgreens On Nacogdoches And O'connor
Degreeworks Sbu
R/Altfeet
Directions To 401 East Chestnut Street Louisville Kentucky
Vanessa West Tripod Jeffrey Dahmer
Samantha Lyne Wikipedia
Trac Cbna
Zoe Mintz Adam Duritz
Site : Storagealamogordo.com Easy Call
Catherine Christiane Cruz
Https Paperlesspay Talx Com Boydgaming
Spn 520211
Amazing Lash Studio Casa Linda
Mybiglots Net Associates
Anotherdeadfairy
Evil Dead Rise Ending Explained
Alternatieven - Acteamo - WebCatalog
Gina's Pizza Port Charlotte Fl
Aladtec Login Denver Health
Ducky Mcshweeney's Reviews
Dallas City Council Agenda
Go Upstate Mugshots Gaffney Sc
Laurin Funeral Home | Buried In Work
The Boogeyman Showtimes Near Surf Cinemas
Dynavax Technologies Corp (DVAX)
Best Restaurant In Glendale Az
ENDOCRINOLOGY-PSR in Lewes, DE for Beebe Healthcare
Wlds Obits
15 Best Things to Do in Roseville (CA) - The Crazy Tourist
Doordash Promo Code Generator
Riverton Wyoming Craigslist
2132815089
Trivago Anaheim California
M&T Bank
Eat Like A King Who's On A Budget Copypasta
Top 1,000 Girl Names for Your Baby Girl in 2024 | Pampers
Iupui Course Search
Hampton In And Suites Near Me
Tito Jackson, member of beloved pop group the Jackson 5, dies at 70
Is Chanel West Coast Pregnant Due Date
San Diego Padres Box Scores
Latest Posts
Article information

Author: Dr. Pierre Goyette

Last Updated:

Views: 6147

Rating: 5 / 5 (50 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Dr. Pierre Goyette

Birthday: 1998-01-29

Address: Apt. 611 3357 Yong Plain, West Audra, IL 70053

Phone: +5819954278378

Job: Construction Director

Hobby: Embroidery, Creative writing, Shopping, Driving, Stand-up comedy, Coffee roasting, Scrapbooking

Introduction: My name is Dr. Pierre Goyette, I am a enchanting, powerful, jolly, rich, graceful, colorful, zany person who loves writing and wants to share my knowledge and understanding with you.