Programming MATLAB
Paul Cotofrei
information management institute master of science in finance
2017
Cell Arrays
Acellarrayisatypeofdatastructurethatcanstoredifferenttypesof values (e.g. vectors, matrix, strings, functions, other cell arrays) in its elements (denoted ’cells’)
Acellarraycouldbeavector(roworcolumn)oramatrix
Itisanarray,soindicesareusedtorefertotheelements
Onegreatapplicationofcellarrays:storingstringsofdifferentlengths!
Thesyntaxusedtocreateacellarrayiscurlybraces{}insteadof[]
Thedirectmethodistoputvaluesintherow(s)separatedbycommas or spaces, and to separate the rows with semicolons (so, same as other arrays, but using { } instead of [ ])
Thecellfunctioncanalsobeusedtopre-allocatebypassingthe dimensions of the cell array, e.g. cell(4, 2)
Examples
Referring to Cell Array Elements
Theelementsincellarraysarecells!
Therearetwomethodsofreferringtopartsofcellarrays:
you can refer to the cells: this is called cell indexing and parentheses are used
you can refer to the contents of the cells: this is called content indexing and curly braces are used
Forexample:
» ca = {2:4, ’hello’};
» ca(1) % the first cell of the cell array ’ca’
ans =
[1×3 double]
» ca{1} % the content of first cell of the cell array
’ca’
ans =
234
» ca{:} % the content of al cells of ’ca’ ans =
234 ans =
’hello’
Comparing cell arrays of strings vs. strings
» A = {’Apple’; ’IBM’; ’Microsoft’} A=
’Apple’ ’IBM’ ’Microsoft’
» size(A) ans =
31
» class(A)
ans = cell
» S = char(’Apple’, ’IBM’, ’Microsoft’) S=
Apple
IBM
Microsoft » size(S) ans =
39
» class(S)
ans = char
» A(2), class(A(2))
ans =
’IBM’ ans =
cell
» A{2}, class(A{2})
ans =
IBM ans =
char » A’
ans =
’Apple’ ’IBM’ ’Microsoft’
Cell Array Functions
Thecelldispfunctiondisplaysthecontentsofallcellsofacell array;
this function behaves recursively: if a cell contains another cell array (let denote it a), the contents of all cells of a are also displayed
cellplotputsagraphicaldisplayinaFigureWindow(butit just shows cells, not their contents)
toconvertfromacharactermatrixtoacellarrayofstrings: cellstr
iscellstrwillreturnlogicaltrueifacellarrayisacellarrayof all strings
Example
» A = {’Apple’; ’IBM’; ’Microsoft’}; % column vector of
cells (3×1)
» B = [1 2; 3 4]; % matrix
» C = @(x) x.^2 + 1; % function
» D = [10 20 30 40 50]; % row vector
» c = {A, B; C, D} % we define a 2×2 cell array c=
{3×1 cell} [2×2 double]
@(x)x.^2+1 [1×5 double]
» celldisp(c)
c{1,1}{1} =
Apple
c{1,1}{2} =
IBM
c{1,1}{3} =
Microsoft
c{2,1} =
@(x)x.^2+1
c{1,2} = 12 34
c{2,2} =
10 20 30 40 50
Example: content indexing with { }
» c{1,1}{3} % content of the third cell of the cell array
c{1,1}
ans =
Microsoft
» c{1,1}{3}(6)
ans = s
» x = [1 2 3];
» c{2,1}(x) % apply the content of the cell c(2, 1), i.e.
a function, on the vector x
ans =
2 5 10
» c{1,2}(2,:) % the second row of the matrix contained
in the cell c(1, 2)
ans =
34
» c{1,2}(1,2)
ans = 2
» c{2,2}(3) % the third element of the vector contained in
the cell c(2,2)
ans =
30
Changing cell array contents
» c{1,1}{2} = ’Google’;
» c{1,2} = 10*c{1,2};
» c{2,2}(3) = 300;
» celldisp(c)
c{1,1}{1} =
Apple
c{1,1}{2} =
Google
c{1,1}{3} =
Microsoft
c{2,1} =
@(x)x.^2+1
c{1,2} = 10 20
30 40
c{2,2} =
10 20 300 40 50
Structure Variables
Structuresstorevaluesofdifferenttypes,infields Fieldsaregivennames;theyarereferredtoas
structurename.fieldname using the dot operator
Structurevariablescanbeinitializedusingthestructfunction, which takes pairs of arguments (field name as a string followed by the value for that field)
» subject = struct(’SubjNo’,123,’Height’,62.5);
» subject.Height
ans =
62.5000
Toprint,dispwilldisplayallfields;fprintfcanonlyprint individual fields
» disp(subject)
SubjNo: 123
Height: 62.5000
» fprintf(’The subject # is %d\n’, subject.SubjNo)
The subject # is 123
Cell Arrays vs. Structs
Cellarraysarearrays,sotheyareindexed
That means that you can loop though the elements in a cell
array – or have MATLAB do that for you by using vectorized code
Structsarenotindexed,soyoucannotloop
However, the field names are mnemonic so it is more clear
what is being stored in a struct
Forexample:variable{1}vs.variable.weight: which is more mnemonic?
Struct example
Accessing Structure Elements
» student
ans =
name: ’Apple, A.’
id: 12345
exams: [85 87 90]
grades: {’B+’ ’B+’ ’A’}
» student.name(5)
ans =
e
» student.exams(2)
ans =
87
» student.grades(3)
ans =
’A’ % third cell
» student.grades{3}
ans =
A % content of the third cell
Vector of Structures
AdatabaseofinformationcanbestoredinMATLABinavector of structures; a vector in which every element is a structure
Forexample,foramedicalexperimentinformationonsubjects might include a subject #, the person’s height, and the person’s weight
Everystructurewouldstore3fields:thesubject#,height,and weight
Thestructureswouldbestoredtogetherinonevectorsothat you could loop through them to perform the same operation on every subject
Example problem
Create the vector of structures, either setting all elements with a single call
or setting each element one by one
» packages = struct(’item_no’, {123, 456, 587}, ’cost’, …
{19.99, 5.99, 11.11}, ’price’, {39.95, 49.99, 33.33},…
’code’, {’g’, ’l’, ’w’});
» packages(1) = struct(’item_no’, 123, ’cost’, 19.99, ’price’,…
39.95, ’code’, ’g’,);
» packages(2) = struct(’item_no’, 456, ’cost’, 5.99, ’price’,…
49.99, ’code’, ’l’,);
» packages(3) = struct(’item_no’, 587, ’cost’, 11.11, ’price’,…
33.33, ’code’, ’w’,);
To print the item number and code fields for all elements
for i = 1:length(packages)
fprintf(’Item %d has a code of %c\n’, packages(i).item_no,…
packages(i).code)
end
Example
We may add a new element in the vector. No need to set all fields. The missing field values can be defined later.
Remark: MATLAB does not check the type of the value you set for a field.
» packages(5).item_no = 999;
» packages(5)
ans =
item_no: 999
cost: []
price: []
code: []
» package(5).code = [1 2 3 4]; % valid assignment !
To extract fields values from multiple elements, use cat: function for concatenating numeric elements along a given dimension
» costs = cat(1, packages(:).cost); % column vector
» prices = cat(2, packages(:).price); % row vector
» codes = cellstr(strvcat(packages(:).code)); % create
first a column vector of strings – strvcat() – and then
transform it in a cell array – cellstr()
Nested Structures
Anestedstructureisastructureinwhichatleastonefieldis another structure
Torefertothe”inner”structure,thedotoperatorwouldhaveto be used twice
e.g. structurename.innerstruct.fieldname
Tocreateanestedstructure,callstothestructfunctioncanbe
nested
Example:createsastructureforacontactthatincludesthe person’s name and phone extension. The name is a struct itself that separately stores the first and last name
» contactinfo = struct(’cname’, struct(’last’, ’Smith’,…
’first’, ’Abe’), ’phoneExt’, ’3456’);
» contactinfo.cname.last
ans =
Smith
Structure Functions
rmfield-removesafieldbutdoesn’talterthevariable
isstruct-returnlogical1iftheargumentisastructure
variable
isfield-receivesastructurevariableandastringandwill return logical 1 if the string is the name of a field within the structure
fieldnames-receivesastructurevariableandreturnsthe names of all of its fields as a cell array
struct2cell-convertastructuretoacellarray