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

How to access data in 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 view a cell array in MATLAB? ›

Call celldisp and specify a cell array as its first input argument. Since the first argument is not a workspace variable, and so does not have a name of its own, specify a name as the second argument. celldisp displays the cell array using this name.

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 open cell array in MATLAB? ›

To access the contents of a cell, enclose indices in curly braces, such as c{1} to return 42 and c{3} to return "abcd" . For more information, see Access Data in Cell Array. Cell arrays are useful for nontabular data that you want to access by numeric index.

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.

How are data in arrays accessed? ›

Indexing: Array elements are accessed using indices, which are typically integers. The indices can start at 0 (zero-based indexing), 1 (one-based indexing), or any other integer, depending on the language and context.

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

Description. ds = cell2dataset( C ) converts a cell array to a dataset array. ds = cell2dataset( C , Name,Value ) performs the conversion using additional options specified by one or more Name,Value pair arguments.

How do cell arrays work in MATLAB? ›

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. Refer to sets of cells by enclosing indices in smooth parentheses, () .

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

Array = a single variable (of any data type) that contains multiple content elements. Cell array = a specific type of array in MATLAB; an array of class cell. This is the "everything" container in MATLAB -- it's essentially a meta data type, or a "container" data type. You can put anything inside a cell.

How do you access elements in an array? ›

To access the elements of an array at a given position (known as the index position), use the element_at() function and specify the array name and the index position: If the index is greater than 0, element_at() returns the element that you specify, counting from the beginning to the end of the array.

How do you access variables in an array? ›

Square brackets ([ ]) are used to access and modify an element in an array using an index. The indexed array variable, for example array[index], can be used anywhere a regular variable can be used, for example to get or assign values.

How do you access the entry of an array in MATLAB? ›

MATLAB Array Indexing

To access elements of a Java® object array, use the MATLAB® array indexing syntax, A(row,column) . In a Java program, the syntax is A[row-1][column-1] .

How to store data in cell array in MATLAB? ›

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. C is a 2-by-3 cell array. You also can use the {} operator to create an empty 0-by-0 cell array.

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

References

Top Articles
Who won the Biden-Trump debate? Biden's freeze draws age concerns
Ahead of Biden-Trump debate, Georgia voters weigh 2024 decision
Cold Air Intake - High-flow, Roto-mold Tube - TOYOTA TACOMA V6-4.0
Windcrest Little League Baseball
Junk Cars For Sale Craigslist
Mcfarland Usa 123Movies
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
La connexion à Mon Compte
Category: Star Wars: Galaxy of Heroes | EA Forums
Edgar And Herschel Trivia Questions
Washington, D.C. - Capital, Founding, Monumental
ExploreLearning on LinkedIn: This month's featured product is our ExploreLearning Gizmos Pen Pack, the…
Eka Vore Portal
5 high school volleyball stars of the week: Sept. 17 edition
Katherine Croan Ewald
Google Flights Missoula
Violent Night Showtimes Near Amc Fashion Valley 18
Fort Mccoy Fire Map
BMW K1600GT (2017-on) Review | Speed, Specs & Prices
Evil Dead Rise Showtimes Near Regal Sawgrass & Imax
Where to eat: the 50 best restaurants in Freiburg im Breisgau
Greyson Alexander Thorn
Rogue Lineage Uber Titles
Booknet.com Contract Marriage 2
CVS Health’s MinuteClinic Introduces New Virtual Care Offering
Gillette Craigslist
The Clapping Song Lyrics by Belle Stars
TJ Maxx‘s Top 12 Competitors: An Expert Analysis - Marketing Scoop
Salemhex ticket show3
Craigslist Scottsdale Arizona Cars
Publix Coral Way And 147
Redding Activity Partners
Does Circle K Sell Elf Bars
Bratislava | Location, Map, History, Culture, & Facts
آدرس جدید بند موویز
Facebook Marketplace Marrero La
Case Funeral Home Obituaries
That1Iggirl Mega
450 Miles Away From Me
Me Tv Quizzes
Www.craigslist.com Waco
15 Best Places to Visit in the Northeast During Summer
Tropical Smoothie Address
Kenwood M-918DAB-H Heim-Audio-Mikrosystem DAB, DAB+, FM 10 W Bluetooth von expert Technomarkt
Bf273-11K-Cl
Costner-Maloy Funeral Home Obituaries
6463896344
Erica Mena Net Worth Forbes
Elvis Costello announces King Of America & Other Realms
Bluebird Valuation Appraiser Login
Competitive Comparison
Predator revo radial owners
Latest Posts
Article information

Author: Lilliana Bartoletti

Last Updated:

Views: 6153

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Lilliana Bartoletti

Birthday: 1999-11-18

Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

Phone: +50616620367928

Job: Real-Estate Liaison

Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.