MATLAB Programming/Cell Arrays

From Wikibooks, open books for an open world
< MATLAB Programming
Jump to: navigation, search


Cell arrays are created just like regular arrays except that curly brackets are used instead of square brackets.

 array = [1, 2, 3; 4, 5, 6];
 cell_array = {1, 2, 3; 4, 5, 6};

The array variable is 1 array with 2 rows and 3 columns. Each element is a scalar. The cell_array variable is essentially an array of arrays. In this case the cell_array variable is made up of 6 arrays with 1 scalar element in each of the 6 arrays.

Cell arrays have fewer limitations than regular arrays. The regular array, defined by the square brackets, can hold numbers or strings but if it holds strings in each element all the strings must be the same length. Also, if 1 element of an array is a string all elements must be a string. Cell arrays have neither of these limitations.

 cell_array = {1, 2, 'a', 'abc'; rand(3, 2), magic(3), eye(3), 'junk'}
   cell_array = 
     [         1]    [         2]    'a'             'abc' 
     [3x2 double]    [3x3 double]    [3x3 double]    'junk' 

With the lack of limitations/rules for the content of a cell array comes complications. These cell arrays are very powerful tools but take a lot of time to get used to because each element can be almost anything.

Cell arrays can also be dynamically resized--a key feature in more advanced data structures. For example, one can create a queue data structure using the commands:
... etc.

Once can pop an element from the front of the queue using the commands:

cell_array(1)=[]; % remove first element - resize
cell_array(1)=[]; % remove first element - resize
... etc.

External Links[edit]