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)

FAQs

What is a cell array? ›

A cell array is a data type with indexed data containers called cells, where each cell can contain any type of data. Cell arrays commonly contain either lists of text, combinations of text and numbers, or numeric arrays of different sizes.

How to add to cell array in MATLAB? ›

Add Cells. A common way to expand a cell array is to concatenate cell arrays vertically or horizontally. Use the standard square bracket concatenation operator [] . Separate elements with semicolons for vertical concatenation or commas for horizontal concatenation.

What does cellfun mean in MATLAB? ›

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

How to use mat2cell function in MATLAB? ›

mat2cell (MATLAB Functions) c = mat2cell(x,m,n) divides up the two-dimensional matrix x into adjacent submatrices, each contained in a cell of the returned cell array, c . Vectors m and n specify the number of rows and columns, respectively, to be assigned to the submatrices in c .

How do I make a cell array in Excel? ›

Be sure to select cells E2:E11, enter the formula =C2:C11*D2:D11, and then press Ctrl+Shift+Enter to make it an array formula. In the sample workbook, select cells E2 through E11. These cells will contain your results.

What is an array function in Excel? ›

You can think of an array as a row or column of values, or a combination of rows and columns of values. Array formulas can return either multiple results, or a single result.

What is the syntax for cell array in MATLAB? ›

Create Cell Array
  • C=2×3 cell array {[ 1]} {[ 2]} {[ 3]} {'text'} {5x10x2 double} {3x1 cell}
  • C3=3×4 cell array {0x0 double} {0x0 double} {0x0 double} {0x0 double} {0x0 double} {0x0 double} {0x0 double} {0x0 double} {0x0 double} {0x0 double} {0x0 double} {0x0 double}

How do you create an array of cells in MATLAB? ›

You can create a cell array in two ways: use the {} operator or use the cell function. When you have data to put into a cell array, use the cell array construction operator {} . Like all MATLAB® arrays, cell arrays are rectangular, with the same number of cells in each row.

How do I check if something is in a cell array in MATLAB? ›

tf = iscell( A ) returns 1 ( true ) if A is a cell array. Otherwise, it returns 0 ( false ).

How to convert cell to array in MATLAB? ›

A = cell2mat( C ) converts a cell array into an ordinary array. The elements of the cell array must all contain the same data type, and the resulting array is of that data type.

What is @() in MATLAB? ›

Description: The @ symbol forms a handle to either the named function that follows the @ sign, or to the anonymous function that follows the @ sign. You can also use @ to call superclass methods from subclasses. Examples. Create a function handle to a named function: fhandle = @myfun.

Is Cellfun faster than for loop MATLAB? ›

cellfun and arrayfun are cool and allow a compact notation. But they are not designed to be faster than loops.

How to concatenate cell arrays in MATLAB? ›

C = cat( dim , A1,A2,…,An ) concatenates A1 , A2 , … , An along dimension dim . You can use the square bracket operator [] to concatenate or append arrays. For example, [A,B] and [A B] concatenates arrays A and B horizontally, and [A; B] concatenates them vertically.

How to use imbinarize function in MATLAB? ›

BW = imbinarize( I , T ) creates a binary image from image I using the threshold value T . T can be a global image threshold, specified as a scalar luminance value, or a locally adaptive threshold, specified as a matrix of luminance values.

How to use mux in MATLAB? ›

The Mux block combines inputs with the same data type and complexity into a virtual vector. You can use multiple Mux blocks to create a mux signal in stages, but the result is flat as if you used a single Mux block. Ideally, use Mux blocks to group only function-call signals.

What is the meaning of cell array? ›

In MATLAB, cell arrays are a type of arrays which stores elements of different data types and sizes in different cells, or one could say that cell arrays allow users to store heterogeneous data into a single array.

What is the benefit of using cell array? ›

One useful application of a cell array is to store strings of different lengths. As cell arrays can store different types of values, strings of different lengths can be stored in the elements. It is possible to convert from a cell array of strings to a character array and vice versa.

What is the difference between solar cell and array? ›

An individual photovoltaic device is known as a solar cell. Due to its size, it produces 1 to 2 watts of electricity, but you can easily increase the power output by connecting cells, which makes up a module or panel. And if you have multiple modules or panels connected together, this is called an array.

What is an array and how does it work? ›

Overview. An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. Depending on the language, array types may overlap (or be identified with) other data types that describe aggregates of values, such as lists and strings.

Top Articles
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 5671

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.