COMP 116: Introduction to Scientific Programming Lecture 25: Cell Arrays and Structures.
-
Upload
milo-potter -
Category
Documents
-
view
224 -
download
0
Transcript of COMP 116: Introduction to Scientific Programming Lecture 25: Cell Arrays and Structures.
COMP 116: Introduction to Scientific Programming
Lecture 25: Cell Arrays and Structures
Announcements and RemindersFriday class will be taught by
Sachin Patil
This Wednesday’s quiz moved to Friday
This Wednesday office hours from 2-3pm
Midterm coming up
Today
How to store variables of different types (numbers, characters, strings, arrays, matrices) all in one single array?
Two options: ◦Cells◦Structs
Data Structures
Arrays◦Homogenous◦Indexing by numbers
Cell Arrays◦Heterogeneous◦Indexing by numbers
Structures◦Heterogeneous◦Accessing by naming
REVIEW: ARRAYS
Multi-dimensional Arrays [42]
◦ Scalar◦ 0-dimensional
[1 2 3 4 5]◦ Vector◦ 1-dimensional
[1 2 3; 4 5 6]◦ Matrix◦ 2-dimensional
We can go higher:◦ Multidimensional array ◦ n-dimensional
N-D arrays3-Dimensional arrays
◦ e.g. temperature at every point in this room (x,y,z)
4-Dimensional arrays◦ e.g. temperature in
this room over time (x,y,z,t)>> A = ones(2,3,2);
>> B(:,:,1) = [1:4; 5:8];
>> B(:,:,2) = [7:10; 13:16];
Most common 3D array
Images◦3 channels (red, green, blue)◦Each channel is a 2D array
Most common 3D array
N-D Arrays: ArithmeticElement-by-Element arithmetic
◦The same as before ◦+ - .* ./ .\ .^
Linear algebra (i.e., matrix) operations generally not used
CELL ARRAYS
>> doc cell
Under Help:MATLAB → Programming Fundamentals → Classes (Data Types) → Cell Arrays
Creating Cell ArraysJust like arrays, but use {} instead of []
Here’s a list of names:◦Alexander the Great◦Winnie the Pooh◦Jack the Ripper◦Stephen the Colbert
Put these into a MATLAB data structure
Creating Cell ArraysJust like arrays, but use {} instead of []
Does this work?◦names = ['Alexander the Great'; 'Winnie the Pooh'; 'Jack the Ripper'; 'Stephen the Colbert']
Simple modification:◦names = {'Alexander the Great'; 'Winnie the Pooh'; 'Jack the Ripper'; 'Stephen the Colbert'}
Cell Arrays
Arrays Cell Arrays
• Elements accessed by indexing using numbers, A(r,c) or A(idx).
• Elements accessed by indexing using numbers, A(r,c) or A(idx)
• Each element in array must all have same type
• Each element can have any type
• Elements of an array are ‘simple’
• Each element can contain another array or cell array
• Strings stored in Arrays must all be same length
• Strings stored in cell arrays can all be different lengths
Note: Not the same concept as cells (%%) in publishable scripts
Creating Cell Arrays
% Cell array of different length strings
days = {'Monday'; 'Tuesday'; ...};
% Cell array of 4 elements (of different sizes, data types)
some_guy = { 'Steve', 45; ...
[8 19 1956], {'ice cream'; 'pizza'} };
% Using 'cell' command
cB = cell(n) % creates n by n cell of empty elements
cC = cell( m, n) % creates m by n cell of empty elements
% Creating a Cell Array from an Array
A = ones(2, 2);
cA = cell(size(A)); % Note: all elements are empty
Accessing Cell Arrays:
% Change content
some_guy{1,1} = 'Chuck'
some_guy{2,2} = 1:5;
some_guy{1,2} = []; % Delete content in cell 1,2
% Grab 1st, 2nd elements
some_guy(1:2)
row2 = some_guy (2,:) % Grab 2nd row of cells
Two ways to access elements: names{2} gives you the contents of a call names(2) gives you a new cell array with those contents
Another useful example
names = {'Sine', 'Cosine'};labels = {'0', 'pi', '2pi', '3pi', '4pi'};t = 0:pi/32:4*pi;plot(t, [sin(t); cos(t)]);legend(names);set(gca, 'XTick', 0:pi:4*pi);set(gca, 'XTickLabel', labels);
Accessing Cell Arrays Remember: crucial distinction between {}
and () operators
Example: A = { false, rand(3); 4.0, 'This
is a string'}; A{1} A{1,1} A(2) A(2,1) A(2,:) A{:,2}
Indices work just as for ‘standard’ arrays.
Useful Commandscelldisp – shows contents of the
cell in the command winow, one element at a time
cellplot – graphical display of all cells in a cell array
Inspecting Cell Arrays A = { false, rand(3); 4.0,
'This is a string'};Try: disp(A) celldisp(A) cellplot(A)
Now try this:
>> B = {A; A} >> D = { B B }>> cellplot(D);
0
4
Practice
A = {4, [1:10]', 'demo'; false, eye(2), rand(3)};
A
B = A(1)
C = A{2}
D = A(2,[2 3])
E = {A{1, [1 3]}, 20}
F = {A(1, [1 3]), 20}
ExamplesCollection of strings
◦Extract important words from a document
ExerciseWrite a function get_the_words
that◦Takes as an input a sentence (in the
form of a string) e.g. ‘This is a true statement’
◦And returns a cell array of the words in the sentence i.e. {‘This’, ‘is’, ‘a’, ‘true’, ‘statement’}
STRUCTURES
Under Help …MATLAB → Programming Fundamentals → Classes (Data Types) → Structures
Structures
Structures Cell Arrays• Elements known by
name• Elements known by
number (indexing).
• Elements called fields• Each field can be any type• But the objects must be consistent
• Each element (cell) can have any type
• Each element inside a structure is given a unique name• These elements are called fields
• Structures are a common concept in most programming languages
StructuresSame example as before, but now
with more data
Name Occupation Birth Fictional
Alexander the Great
Conqueror 356 BC No
Winnie the Pooh Bear 1926 Yes
Jack the Ripper Serial Killer 1800s No
Stephen the Colbert
Political Pundit
1964 Hmm
StructuresUse named ‘fields’ for each
variablealex.name = 'Alexander the Great';alex.occupation = 'Conqueror';alex.birth = 356;alex.fictional = false;
StructuresUse named ‘fields’ for each
variable
Use the struct() function, with name-value pairs
alex.name = 'Alexander the Great';alex.occupation = 'Conqueror';alex.birth = 356;alex.fictional = false;
alex = struct('name', 'Alexander the Great',...'occupation', 'Conqueror', ...'birth', 356, ...'fictional' = false);
Structure Arrays
Each individual structure object is accessed with its index (just as in vectors)
Each field inside an individual structure is found by naming using the '.' operator for access.
characters(1) = alex;characters(2).name = 'Winnie the Pooh';characters(2).occupation = 'Bear';...characters(3) = struct('name', 'Jack the Ripper',...);
Structure ArraysOne way to initialize is to use a
‘template’% create structure layout% note the use of default values and empty arraystemplate = struct( 'name', 'no name', ... 'nickname', 'no name', ... 'emails', [], ... 'department', 'undeclared', ... 'type', 'undergrad', ... 'year', 1 );
% create structure array students = repmat( template, 1, 30 );
% now fill in each structure in the array
ExamplesNested records
◦Structures can contain other structures (or cell arrays) as named fields.
class.instructor = struct('name', {' Vishal' ‘Verma'});class.students = students; % this is a struct arrayclass.building = 'FB';class.room = 7;
ExamplesBuilt-in structures
◦Figures
get(gcf) ◦File lists
>> files = dirfiles = 8x1 struct array with fields: name date bytes isdir datenum
ExamplesThe dir function returns a
structure array with 4 fields: name, date, byte, isdir◦The input of dir is a path
How do we use this to find out the total size of all the files in a directory?
How do we get all of the names of all images in a folder?
Common PitfallsRemember the difference between {} and
() when accessing cell◦ () returns cells◦{} returns contents
Correctly access the field of a structure via the dot operator and the fieldname.◦currStudent.name = 'Steve';
Remember: you still need the index () operator for working with Structure arrays◦students(7).score = 97;
Style GuidelinesUse arrays when all elements are the same
type and in some sense represent the same thing (just different values)
Use cell arrays or structures when the values that make up the object are logically grouped but not the same type or the same thing.◦ Prefer cell arrays when you want to loop through all
elements in each individual cell via indexing.◦ Prefer structures when you want to name each
element individually
Use cell arrays for storing an array of strings.
SummaryReview Cell Arrays & Structures
doc cell MATLAB → Programming Fundamentals →
Classes (Data Types) → Cell Arrays MATLAB → Programming Fundamentals →
Classes (Data Types) → Structures
Practice working with Cell Arrays Structures Operators for Cell Arrays & Structures
{}, (), '.'
Useful functionsrmfield – removes a field from a
structureisstruct – tests whether a
variable is of type structureisfield – tests whether a name
string is a field in the specified structure.
fieldnames – returns names of all fields in a struture.