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
Structs
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
tpl2=setfield(tpl,'weight',98)
will create a new variable with an extra field, and
tpl3=rmfield(tpl,'height')
will will create a new variable with a field less.
Cells
Like structs, cell arrays can contain dissimilar elements. Unlike structs, the elements are indexed by number. So
tplcell{1}='tim'; tplcell{2}='love'; tplcell{3}=1.73;
(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{1}=1; pyramid{2}=[2 3; 4 5]; pyramid{3}=[6 7 8 ; 9 10 11; 12 13 14]; celldisp(pyramid)
The cellfun function can be used to find out about a cell array. For example,
cellfun('isclass',pyramid,'double')
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.
Converting
cells and matrices
A matrix can be converted to a cell array
A=1:4 Acell=num2cell(A)
but because the elements of a cell can be differently sized matrices, cells can't always be converted to matrices. The following would work
Amat=cell2mat(Acell)
cells and structs
When you convert a cell to a struct you need to give some fieldnames
newtpl=cell2struct(tplcell,{'firstname','familyname','height'},2)
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
newtpl=cell2struct(tplcell,{'firstname'})
works, though in this case isn't very useful.
The fieldnames are lost when converting the other way
tplcell2=struct2cell(tpl)