views:

201

answers:

2

I am a little confused about the usage of cells and arrays in MATLAB and would like some clarification on a few points. Here are my observations:

  1. An array can dynamically adjust its own memory to allow for a dynamic number of elements, while cells seem to not act in the same way:

    a=[]; a=[a 1]; b={}; b={b 1};
    
  2. Several elements can be retrieved from cells, but it doesn't seem like they can be from arrays:

    a={'1' '2'}; figure; plot(...); hold on; plot(...); legend(a{1:2});   
    b=['1' '2']; figure; plot(...); hold on; plot(...); legend(b(1:2));
    %# b(1:2) is an array, not its elements, so it is wrong with legend.
    

Are these correct? What are some other different usages between cells and array?

+6  A: 

Cell arrays can be a little tricky since you can use the [], (), and {} syntaxes in various ways for creating, concatenating, and indexing them, although they each do different things. Addressing your two points:

  1. To grow a cell array, you can use one of the following syntaxes:

    b = [b {1}];     %# Make a cell with 1 in it, and append it to the existing
                     %#   cell array b using []
    b = {b{:} 1};    %# Get the contents of the cell array as a comma-separated
                     %#   list, then regroup them into a cell array along with a
                     %#   new value 1
    b{end+1} = 1;    %# Append a new cell to the end of b using {}
    b(end+1) = {1};  %# Append a new cell to the end of b using ()
    
  2. When you index a cell array with (), it returns a subset of cells in a cell array. When you index a cell array with {}, it returns a comma-separated list of the cell contents. For example:

    b = {1 2 3 4 5};  %# A 1-by-5 cell array
    c = b(2:4);       %# A 1-by-3 cell array, equivalent to {2 3 4}
    d = [b{2:4}];     %# A 1-by-3 numeric array, equivalent to [2 3 4]
    

    For d, the {} syntax extracts the contents of cells 2, 3, and 4 as a comma-separated list, then uses [] to collect these values into a numeric array. Therefore, b{2:4} is equivalent to writing b{2},b{3},b{4}, or 2,3,4.

    With respect to your call to LEGEND, the syntax legend(a{1:2}) is equivalent to legend(a{1},a{2}), or legend('1','2'). Thus two arguments (two separate characters) are passed to LEGEND. The syntax legend(b(1:2)) passes a single argument, which is a 1-by-2 string '12'.

gnovice
+2  A: 

Every cell array is an array! From this answer:

[] is an array-related operator. An array can be of any type - array of numbers, char array (string), struct array or cell array. All elements in an array must be of the same type!

Example: [1,2,3,4]

{} is a type. Imagine you want to put items of different type into an array - a number and a string. This is possible with a trick - first put each item into a container {} and then make an array with these containers - cell array.

Example: [{1},{'Hallo'}] with shorthand notation {1, 'Hallo'}

Mikhail