Access Data in Cell Array - MATLAB & Simulink - MathWorks Deutschland (2024)

Open Live Script

Basic Indexing

A cell array is a data type with indexed data containers called cells. Each cell can contain any type of data. Cell arrays are often used to hold data from a file that has inconsistent formatting, such as columns that contain both numeric and text data.

For instance, consider a 2-by-3 cell array of mixed data.

C = {'one','two','three'; 100,200,rand(3,3)}
C=2×3 cell array {'one'} {'two'} {'three' } {[100]} {[200]} {3x3 double}

Each element is within a cell. If you index into this array using standard parentheses, the result is a subset of the cell array that includes the cells.

C2 = C(1:2,1:2)
C2=2×2 cell array {'one'} {'two'} {[100]} {[200]}

To read or write the contents within a specific cell, enclose the indices in curly braces.

R = C{2,3}
R = 3×3 0.8147 0.9134 0.2785 0.9058 0.6324 0.5469 0.1270 0.0975 0.9575
C{1,3} = 'longer text in a third location'
C=2×3 cell array {'one'} {'two'} {'longer text in a third location'} {[100]} {[200]} {3x3 double }

To replace the contents of multiple cells at the same time, use parentheses to refer to the cells and curly braces to define an equivalently sized cell array.

C(1,1:2) = {'first','second'}
C=2×3 cell array {'first'} {'second'} {'longer text in a third location'} {[ 100]} {[ 200]} {3x3 double }

Read Data from Multiple Cells

Most of the data processing functions in MATLAB® operate on a rectangular array with a uniform data type. Because cell arrays can contain a mix of types and sizes, you sometimes must extract and combine data from cells before processing that data. This section describes a few common scenarios.

Text in Specific Cells

When the entire cell array or a known subset of cells contains text, you can index and pass the cells directly to any of the text processing functions in MATLAB. For instance, find where the letter t appears in each element of the first row of C.

ts = strfind(C(1,:),'t')
ts=1×3 cell array {[5]} {0x0 double} {[8 11 18 28]}

Numbers in Specific Cells

The two main ways to process numeric data in a cell array are:

  • Combine the contents of those cells into a single numeric array, and then process that array.

  • Process the individual cells separately.

To combine numeric cells, use the cell2mat function. The arrays in each cell must have compatible sizes for concatenation. For instance, the first two elements of the second row of C are scalar values. Combine them into a 1-by-2 numeric vector.

v = cell2mat(C(2,1:2))
v = 1×2 100 200

To process individual cells, you can use the cellfun function. When calling cellfun, specify the function to apply to each cell. Use the @ symbol to indicate that it is a function and to create a function handle. For instance, find the length of each of the cells in the second row of C.

len = cellfun(@length,C(2,:))
len = 1×3 1 1 3

Data in Cells with Unknown Indices

When some of the cells contain data that you want to process, but you do not know the exact indices, you can use one of these options:

  • Find all the elements that meet a certain condition using logical indexing, and then process those elements.

  • Check and process cells one at a time with a for- or while-loop.

For instance, suppose you want to process only the cells that contain character vectors. To take advantage of logical indexing, first use the cellfun function with ischar to find those cells.

idx = cellfun(@ischar,C)
idx = 2x3 logical array 1 1 1 0 0 0

Then, use the logical array to index into the cell array, C(idx). The result of the indexing operation is a column vector, which you can pass to a text processing function, such as strlength.

len = strlength(C(idx))
len = 3×1 5 6 31

The other approach is to use a loop to check and process the contents of each cell. For instance, find cells that contain the letter t and combine them into a string array by looping through the cells. Track how many elements the loop adds to the string array in variable n.

n = 0;for k = 1:numel(C) if ischar(C{k}) && contains(C{k},"t") n = n + 1; txt(n) = string(C{k}); endendtxt
txt = 1x2 string "first" "longer text in a third location"

Index into Multiple Cells

If you refer to multiple cells using curly brace indexing, MATLAB returns the contents of the cells as a comma-separated list. For example,

C{1:2,1:2}

is the same as

C{1,1}, C{2,1}, C{1,2}, C{2,2}.

Because each cell can contain a different type of data, you cannot assign this list to a single variable. However, you can assign the list to the same number of variables as cells.

[v1,v2,v3,v4] = C{1:2,1:2}
v1 = 'first'
v2 = 100
v3 = 'second'
v4 = 200

If each cell contains the same type of data with compatible sizes, you can create a single variable by applying the array concatenation operator [] to the comma-separated list.

v = [C{2,1:2}]
v = 1×2 100 200

If the cell contents cannot be concatenated, store results in a new cell array, table, or other heterogeneous container. For instance, convert the numeric data in the second row of C to a table. Use the text data in the first row of C for variable names.

t = cell2table(C(2,:),VariableNames=C(1,:))
t=1×3 table first second longer text in a third location _____ ______ _______________________________ 100 200 {3x3 double} 

Index into Arrays Within Cells

If a cell contains an array, you can access specific elements within that array using two levels of indices. First, use curly braces to access the contents of the cell. Then, use the standard indexing syntax for the type of array in that cell.

For example, C{2,3} returns a 3-by-3 matrix of random numbers. Index with parentheses to extract the second row of that matrix.

C{2,3}(2,:)
ans = 1×3 0.9058 0.6324 0.5469

If the cell contains a cell array, use curly braces for indexing, and if it contains a structure array, use dot notation to refer to specific fields. For instance, consider a cell array that contains a 2-by-1 cell array and a scalar structure with fields f1 and f2.

c = {'A'; ones(3,4)};s = struct("f1",'B',"f2",ones(5,6)); C = {c,s}
C=1×2 cell array {2x1 cell} {1x1 struct}

Extract the arrays of ones from the nested cell array and structure.

A1 = C{1}{2}
A1 = 3×4 1 1 1 1 1 1 1 1 1 1 1 1
A2 = C{2}.f2
A2 = 5×6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

You can nest any number of cell and structure arrays. Apply the same indexing rules to lower levels in the hierarchy. For instance, these syntaxes are valid when the referenced cells contain the expected cell or structure array.

C{1}{2}{3}

C{4}.f1.f2(1)

C{5}.f3.f4{1}

At any indexing level, if you refer to multiple cells, MATLAB returns a comma-separated list. For details, see Index into Multiple Cells.

See Also

cell | cell2mat | cellfun

Related Topics

  • Add or Delete Cells in Cell Array
  • Array Indexing
  • Comma-Separated Lists
Access Data in Cell Array
- MATLAB & Simulink
- MathWorks Deutschland (2024)

FAQs

Access Data in Cell Array - MATLAB & Simulink - MathWorks Deutschland? ›

First, use curly braces to access the contents of the cell. Then, use the standard indexing syntax for the type of array in that cell. For example, C{2,3} returns a 3-by-3 matrix of random numbers.

How do you access parts of an array in MATLAB? ›

When you want to access selected elements of an array, use indexing. Using a single subscript to refer to a particular element in an array is called linear indexing. If you try to refer to elements outside an array on the right side of an assignment statement, MATLAB throws an error.

How to add data 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.

How do you convert a cell array to data in MATLAB? ›

ds = cell2dataset( C ) converts a cell array to a dataset array.

How to access data within a struct in MATLAB? ›

Structures store data in containers called fields, which you can then access by the names you specify. Use dot notation to create, assign, and access data in structure fields. If the value stored in a field is an array, then you can use array indexing to access elements of the array.

How do you access the contents of a cell array in MATLAB? ›

If a cell contains an array, you can access specific elements within that array using two levels of indices. First, use curly braces to access the contents of the cell. Then, use the standard indexing syntax for the type of array in that cell.

How do you access data inside an array? ›

We can access the data inside arrays using indexes . Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use zero-based indexing, so the first element in an array is element 0.

What is the difference between array and cell array in MATLAB? ›

A structure array is a data type that groups related data using data containers called fields. Each field can contain any type of data. A cell array is a data type with indexed data containers called cells, where each cell can contain any type of data.

How to table to cell array in MATLAB? ›

C = table2cell( T ) converts the table or timetable, T , to a cell array, C . Each variable in T becomes a column of cells in C .

How do you turn a cell array into a string in MATLAB? ›

Direct link to this answer
  1. To convert a cell array of character vectors to a character array, use the “char” function.
  2. To extract the contents from a cell, index using curly braces.
  3. Starting in R2016b, you can store text in string arrays. To convert a cell array to a string array, use the “string” function.
Feb 1, 2015

How do you convert text to cell array in MATLAB? ›

C = cellstr( A ) converts A to a cell array of character vectors. For instance, if A is a string, "foo" , C is a cell array containing a character vector, {'foo'} . C = cellstr( A , dateFmt ) , where A is a datetime or duration array, applies the specified format, such as "HH:mm:ss" .

How to convert array of cells to cell array in MATLAB? ›

C = num2cell( A ) converts array A into cell array C by placing each element of A into a separate cell in C . The num2cell function converts an array that has any data type—even a nonnumeric type.

How to export cell array to text MATLAB? ›

You can export a cell array from MATLAB® workspace into a text file in one of these ways:
  1. Use the writecell function to export the cell array to a text file.
  2. Use fprintf to export the cell array by specifying the format of the output data.

How do you access data in a struct? ›

It is easy to access the variable of C++ struct by simply using the instance of the structure followed by the dot (.) operator and the field of the structure.

How do you access an array in a struct? ›

You use a dot operator and then a subscript operator. The operators access the array of structs in the following order: The dot operator locates elements with the same name from each of the structs and returns an array. The subscript operator accesses the indexed element in the array.

How do you enter data into MATLAB? ›

Open the Import Tool
  1. MATLAB Toolstrip: On the Home tab, in the Variable section, click Import Data.
  2. MATLAB command prompt: Enter uiimport( filename ) , where filename is a character vector specifying the name of a text or spreadsheet file (or, in MATLAB Online, an HDF5 or netCDF file).

How do you access a specific part of an array? ›

Array index starts with 0 to represent the first element of an array, 1 for the second element and so on. For example, given an array ["apple", "banana", "orange", "grape"], if you want to target the third element "orange", you would use the index 2 since counting starts from 0.

How do you access the elements of an array? ›

Access Array Elements

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you reference part of an array in MATLAB? ›

The most common way is to explicitly specify the indices of the elements. For example, to access a single element of a matrix, specify the row number followed by the column number of the element. e is the element in the 3,2 position (third row, second column) of A .

How do you access each object in an array? ›

To access an element from an array, you reference the array name, followed by a pair of square brackets containing the index of the element you want to access. Arrays are zero-indexed, which means the first element in the array has an index of 0, the second element has an index of 1, and so on.

Top Articles
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 5675

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.