|
|
|||
![]() |
Department of Engineering |
| University of Cambridge > Engineering Department > computing help > programs > matlab |
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.
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.
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)
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)
| | computing help | Matlab | |