Department of Engineering

IT Services

Matlab cells and structs

Matlab uses vectors heavily. Matlab vectors are like arrays in fortran or C++ - the elements are all the same type and are indexed using numbers. But there are other ways to organise data structures in matlab


In C/C++ and newer fortrans one can bundle together elements of various types into a structure. This helps keep the code tidy - e.g. if your program deals with information about people (names, heights, etc) it makes sense to gather together all the info about a person into one variable.

 tpl = struct ('forename', 'Tim', 'surname', 'Love', 'height', 1.73)

creates a variable called tpl containing 3 parts (called 'fields') that can be individually accessed - e.g. tpl.height=1.75; is possible. If you write a function that needed all the information about tpl you just pass tpl as an argument, which is much tidier than passing a list of values. Typing

   isstruct (tpl)

will check whether tpl is a struct. Typing

   fieldnames (tpl)

will list the fields. Doing


will create a new variable with an extra field, and


will will create a new variable with a field less.


Like structs, cell arrays can contain dissimilar elements. Unlike structs, the elements are indexed by number. So


(note the curly brackets!) creates a cell array with 3 elements. Typing length(tplcell) will return 3, and iscell(tplcell) will return 1 (i.e. true).

tplcell and tpl contain the same information. Sometimes a cell array is more appropriate than a struct - it depends on the situation.

Variously-sized vectors and matrices can be elements of a cell array, so for example if you wanted to represent a square-based pyramid you could do

pyramid{2}=[2 3; 4 5];
pyramid{3}=[6 7 8 ; 9 10 11; 12 13 14];

The cellfun function can be used to find out about a cell array. For example,


tells you that all of the elements of pyramid are standard matlab matrices.

Cell arrays can contain the same data as matrices. Some routines (e.g. union) accept them interchangeably. You can also have matrices of structures, cell arrays of structs, etc.


cells and matrices

A matrix can be converted to a cell array


but because the elements of a cell can be differently sized matrices, cells can't always be converted to matrices. The following would work


cells and structs

When you convert a cell to a struct you need to give some fieldnames


The final "2" argument (denoting the 2nd dimension) is necessary because otherwise the structure created will have 1 field of 3 elements and the cell2struct call will only need 1 fieldname, so


works, though in this case isn't very useful.

The fieldnames are lost when converting the other way