Loren on the Art of MATLAB

Turn ideas into MATLAB

Cell Arrays and Their Contents

I've written several blog articles so far on structures, and not quite so much on their soulmates, cell arrays. Just last week, at the annual MathWorks Aerospace Defense Conference (MADC), I had several people ask for help on cell arrays and indexing. Couple that with the weekly questions on the MATLAB newsgroup, and it's time.  



As you probably already know, arrays in MATLAB are rectangular looking in any two dimensions. For example, for each row in a matrix (2-dimensional), there is the same number of elements - all rows have the same number of columns. To denote missing values in floating point arrays, we often use NaN. And each MATLAB array is homogeneous; that is, each array element is the same kind of entity, for example, double precision values.

Cell Arrays

Cell arrays were introduced in MATLAB 5.0 to allow us to collect arrays of different sizes and types. Cell arrays themselves must still be rectangular in any given two dimensions, and since each element is a cell, the array is filled with items that are all the same type. However, the contents of each cell can be any MATLAB array, including
  • numeric arrays, the ones that people typically first learn
  • strings
  • structures
  • cell arrays

Indexing Using Parentheses

Indexing using parentheses means the same thing for all MATLAB arrays. Let's take a look at a numeric array first and then a cell array.
M = magic(3)
M =
     8     1     6
     3     5     7
     4     9     2
Let's place a single element into another array.
s = M(1,2)
s =
Next let's get a row of elements.
row3 = M(3,:)
row3 =
     4     9     2
And now grab the corner elements.
corners = M([1 end],[1 end])
corners =
     8     6
     4     2
What's in the MATLAB workspace?
clear % clean up before we move forward
  Name          Size                    Bytes  Class

  M             3x3                        72  double array
  corners       2x2                        32  double array
  row3          1x3                        24  double array
  s             1x1                         8  double array

Grand total is 17 elements using 136 bytes
Next, let's do similar experiments with a cell array.
C = {magic(3) 17 'fred'; ...
    'AliceBettyCarolDianeEllen' 'yp' 42; ...
    {1} 2 3}
C = 
    [3x3  double]    [17]    'fred'
    [1x25 char  ]    'yp'    [  42]
    {1x1  cell  }    [ 2]    [   3]
Notice the information we get from printing C. We can see it is 3x3, and we can see information, but not necessary full content, about the values in each cell. The very first cell contains a 3x3 array of doubles, the second element in the first row contains the scalar value 17, and the third cell in the first row contains a string, one that is short enough to print out. Let's place a single element into another array.
sCell = C(1,2)
sCell = 
Next let's get a row of elements.
row3Cell = C(3,:)
row3Cell = 
    {1x1 cell}    [2]    [3]
And now grab the corner elements.
cornersCell = C([1 end],[1 end])
cornersCell = 
    [3x3 double]    'fred'
    {1x1 cell  }    [   3]
What's in our workspace now?
clear sCell row3Cell cornersCell
  Name              Size                    Bytes  Class

  C                 3x3                       774  cell array
  cornersCell       2x2                       396  cell array
  row3Cell          1x3                       264  cell array
  sCell             1x1                        68  cell array

Grand total is 84 elements using 1502 bytes

An Observation about Indexing with Parentheses

When we index into an array using parentheses, (), to extract a portion of an array, we get an array of the same type. With the double precision array M, we got double precision arrays of different sizes and shapes as our output. When we do the same thing with our cell array C, we get cell arrays of various shapes and sizes for the output.

Contents of Cell Arrays

Cell arrays are quite useful in a variety of applications. We use them in MATLAB for collecting strings of different lengths. They are good for collecting even numeric arrays of different sizes, e.g., the magic squares from order 3 to 10. But we still need to get information from within given cells, not just create more cell arrays using (). To do so, we use curly braces {}. I used one set of them to create C initially. Now let's extract the contents from some cells and assign the output to an array. Let's place a single element into another array.
m = C{1}
m =
     8     1     6
     3     5     7
     4     9     2
Next let's try to get a row of elements.
    row3 = C{3,:}
    lerr = lasterror;
Illegal right hand side in assignment. Too many elements.
Why couldn't I do that? Let's look at what's in row 1.
ans = 
    [3x3 double]    [17]    'fred'
Now let's see what we get if we look at the contents without assigned the output to a variable.
ans =
     8     1     6
     3     5     7
     4     9     2
ans =
ans =
You can see that we assign to ans three times, one for each element in the row of the cell array. It's as if we wrote this expression: C{1,1},C{1,2},C{1,3} with the output from these arrays being successively assigned to ans. MATLAB can't typically take the content from these cells and place them into a single array. We could extract the contents of row 1, one cell at a time as we did to create m. If we want to extract more cells at once, we have to place the contents of each cell into its own separate array, like this,
[c11 c12 c13] = C{1,:}
c11 =
     8     1     6
     3     5     7
     4     9     2
c12 =
c13 =
taking advantage of syntax new in MATLAB Release 14 for assignment when using comma-separated lists.

Cell Array Indexing Summary

  • Use curly braces {} for setting or getting the contents of cell arrays.
  • Use parentheses () for indexing into a cell array to collect a subset of cells together in another cell array.
Here's my mnemonic for remembering when to use the curly braces: curly for contents Does anyone have any mnemonics or other special ways to help remember when to use the different kinds of indexing? If so, please post a comment below.


Published with MATLAB® 7.2
  • print
  • send email


댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.