In-Service Workshop on Statistical Methods

Download Report

Transcript In-Service Workshop on Statistical Methods

COS 131: Computing for Engineers
Chapter 7: Cell Arrays and
Structures
Laura Broussard, Ph.D.
Visiting Professor
July 21, 2015
1
Introduction
• Addresses the nature, implementation, and
behavior of collections that may contain data items
of any class, size, or shape.
• Have applications where we must group data of
different types in a common, logical structure.
This is where we use cell arrays and structures.
• Two different heterogeneous storage mechanisms:
– Those accessed by index (cell arrays)
– Those accessed by name (structures)
– Will also consider collecting structures into arrays of
structures
July 21, 2015
2
Introduction
• Considers data collections that are more general
and flexible than the arrays we have considered
thus far.
• These collections may contain objects of any type,
rather than just numbers
• None of the operations defined for numerical
arrays can be applied to cell arrays and structures
• To perform operations on their contents, the items
must be extracted one at a time and replaced if
necessary
July 21, 2015
3
Introduction
• Consider three different mechanisms for
building heterogeneous collections:
– Cell arrays index their contents with a
numerical index
– Structures index their contents with a symbolic
index
– Structure arrays index structures with a
numerical index
July 21, 2015
4
Concept: Collecting Dissimilar Objects
• Heterogeneous collections permit objects of
different data types to be grouped in a
collection
• Collections may be of any data type
severely restricts the operations that can be
performed on the collections as a whole
• Algorithms that process heterogeneous
collections must deal with the data contents
one item at a time
July 21, 2015
5
Cell Arrays
• Cell arrays, as the name suggests, have the
general form of arrays and can be indexed
numerically as arrays
• Each element of a cell array should be
considered as a container in which one data
object of any class can be stored
• Can be treated as arrays of containers for
the purpose of concatenation and slicing
• Cells must be accessed individually
July 21, 2015
6
Cell Arrays
• Creating Cell Arrays
– Cell arrays may be constructed in the following ways:
• By assigning values individually to a variable indexed with braces:
July 21, 2015
7
Cell Arrays
• Creating Cell Arrays
– Cell arrays may be constructed in the following ways:
• By assigning container individually to a variable indexed with
brackets:
>> B[1] = {[4 6]}
B =
[ 1x2 double]
July 21, 2015
8
Cell Arrays
• Creating Cell Arrays
– Cell arrays may be constructed in the following ways:
• By concatenating cell contents using braces {…}:
July 21, 2015
9
Cell Arrays
• Creating Cell Arrays
– Cell arrays may be constructed in the following ways:
• By concatenating cell containers:
July 21, 2015
10
Cell Arrays
• Creating Cell Arrays
– From these examples we observe the following:
• A cell array can contain any legal MATLAB object
• Cell arrays can be created “on the fly” by assigning values to an
indexed variable
• Note that the display of cell arrays is different from that of the
contents of a number array; individual numbers are shown in
brackets; larger numerical arrays display their size; character strings
are displayed with the enclosing single quotes
July 21, 2015
11
Cell Arrays
• Accessing Cell Arrays
– Since cell arrays can be considered as conventional arrays of
containers, the container can be accessed and manipulated
normally:
Note: MATLAB returns the array
Dimensions and data type and NOT
The contents as shown in the text.
Note: Braces are used to access the
Contents of the containers.
July 21, 2015
12
Cell Arrays
• Accessing Cell Arrays
– If the right-hand side of an assignment statement results in
multiple cell arrays, the assignment must be to the same
number of variables.
– MATLAB function deal(…) is used to make these
allocations
– Exercise 7.1: Cell arrays
– Smith text, page 159-160, bottom-top
July 21, 2015
13
Cell Arrays
• Accessing Cell Arrays
– Observations:
• When we extract the contents of multiple cells using A{1,2}, this
results in multiple assignments being made
• Fundamental mechanism behind returning multiple results from a
function
• Multiple assignments cannot be made to a single variable
• Cell arrays can be “sliced” with normal vector indexing assignments
as long as the sizes match on the left and right sides of the
assignment
• Unassigned array elements are filled with an empty vector
July 21, 2015
14
Cell Arrays
• Accessing Cell Arrays
– Observations:
• Consider the error here:
– B{[1 3]} = A{[1 2]}
– ??? Cell contents assignment to a non-cell array object.
• Since A{[1 2]} produces two separate assignments, MATLAB will
not assign the answers, even to the right number of places in another
cell array
• Again, the deal(…) function is provided to capture these multiple
results in different variables.
• Note difference between A{:} and A as a parameter to deal(…)
• When deal(…) is provided with a parameter other than a collection
of cells, it copies that parameter to each variable
July 21, 2015
15
Cell Arrays
• Accessing Cell Arrays
– Observations:
• Assignments work normally if cell arrays are treated as vectors and
the extraction of items can be indexed
• Notice that when accessing cell arrays, it is normal to have braces on
one side or the other of an assignment; rare to have braces on both
sides of an assignment; result here is that a cell array is loaded into
the third container in the cell array
July 21, 2015
16
Cell Arrays
• Using Cell Arrays
– A number of uses for cell arrays in MATLAB
• Containing lists of possible values for switch/case statements
• Substituting for parameter lists in function calls
– Listing 7.1: Using cell arrays of parameters
Note: function largest is a hypothetical
function that does not work in MATLAB.
Could you write such a function?
5 points extra credit if you document the
correct use of a function largest as used
here by the next project due date.
July 21, 2015
17
Cell Arrays
• Processing Cell Arrays
– General template for processing cell arrays:
July 21, 2015
18
Cell Arrays
• Processing Cell Arrays
– Checking the class of the element can be achieved in one of
two ways:
• The function class(item) returns a string specifying the item type that
can be used in a SWITCH statement
• Individual test functions can be used in an IF… ELSEIF construct;
examples of the individual test functions are
–
–
–
–
–
–
July 21, 2015
isa(item, ‘class’)
iscell(…)
ischar(…)
islogical(…)
isnumeric(…)
isstruct(…)
19
Cell Arrays
• Processing Cell Arrays
– Listing 7.2: Cell array processing example
July 21, 2015
20
Cell Arrays
• Processing Cell Arrays
– Observations on Listing 7.2
• Function extracts each item in turn in line 6
• Line 7 determines whether this item is of type DOUBLE
• We proceed to line 8 on condition
– Line 8 accumulates the number of items in this array
– The size(…) function returns a vector of the sizes of each dimension
– The total number of numbers is then the product of these values
July 21, 2015
21
MATLAB Structures
• Structures allow items in the collection to be indexed
by a field name
• A field name is typically the name of a local variable
or substructure
• Data contained in a structure is referenced by field
name; example: item1
• Rules for making a field name are the same as those
for a variable
• Fields of a structure are heterogeneous like cell arrays
July 21, 2015
22
MATLAB Structures
• Constructing and Accessing One Structure
– To set the values of items in a structure A, the syntax is as
follows:
July 21, 2015
23
MATLAB Structures
• Constructing and Accessing One Structure
– MATLAB displays the elements of an emerging structure by
name
– Fields in a structure are accessed in the same way-by using
the dotted notation
July 21, 2015
24
MATLAB Structures
• Constructing and Accessing One Structure
– Can determine the names of the fields in a structure using
the built-in function fieldnames(...)
– Returns a cell array containing the field names as strings
July 21, 2015
25
MATLAB Structures
• Constructing and Accessing One Structure
– Fields can also be accessed “indirectly” by setting a variable
to the name of the field, and then using parentheses to
indicate that the variable contents should be used as the field
name:
July 21, 2015
26
MATLAB Structures
• Constructing and Accessing One Structure
– Can also remove a field from a structure using the built-in
function rmfield(…)
– Exercise 7.2: Building structures
– Smith text, page 164, bottom
– Note that since a structure may contain any object, it is quite
legal to make a structure containing a date and insert that
structure in the date field of the entry
July 21, 2015
27
MATLAB Structures
• Constructor Functions
– Constructor functions - Functions that assign their
parameters to the fields of a structure and then return that
structure
– Do this rather than doing it manually for the following
reasons:
• Manual entry can result in strange behavior due to typographical
errors or having fields in the wrong order
• Resulting code is generally more compact and easier to understand
• When constructing collections of structures, it enforces consistency
across the collections
July 21, 2015
28
MATLAB Structures
• Constructor Functions
– Two approaches to the use of constructor functions:
• Using built-in MATLAB capabilities
• Writing your own constructor
– MATLAB built-in function, struct(…) consumes pairs of
entries (each consisting of a field name as a string and a cell
array of field contents) and produces a structure
July 21, 2015
29
MATLAB Structures
• Constructor Functions
– Useful in general to create structures
– Repetition of the field names is annoying and potentially
inefficient
– Can create a special purpose function that “knows” the
necessary field names to create multiple structures in an
organized way
July 21, 2015
30
MATLAB Structures
• Constructor Functions
– Listing 7.3: Constructor function for a CD structure
– Exercise 7.3: A CD structure
– Smith text, page 166, middle
July 21, 2015
31
Structure Arrays
• To be useful, collections like address books and CD
collections require multiple structure entries with the
same fields
• Accomplished by forming an array of data items, each
of which contains the same fields of information
• Resulting data structure is termed a structure array
• Frequent application with database technologies
July 21, 2015
32
Structure Arrays
• Constructing Structure Arrays
– Structure arrays can be created either by
• Creating values for individual fields
• Using MATLAB’s struct(…) function to build the whole structure
array
• Using a custom function to create each individual structure
– Example here is our makeCD(…) function
– Exercise 7.4: Building a structure array “by hand”
– Smith text, page 167, middle
July 21, 2015
33
Structure Arrays
• Constructing Structure Arrays
– Listing 7.4: Building a structure array using struct(…)
July 21, 2015
34
Structure Arrays
• Accessing Structure Elements
– Items can be stored and retrieved by their index in the array
– As structures are added to the array, MATLAB forces all
elements in the structure array to implement the same field
names in the same order
– Elements can be accessed either manually (not
recommended) or by creating new structures with a
constructor and adding them (recommended)
July 21, 2015
35
Structure Arrays
• Accessing Structure Elements
– Listing 7.5: Building a structure array using a custom
constructor
July 21, 2015
36
Structure Arrays
• Accessing Structure Elements
– Should you elect to manipulate them manually, you merely
identify the array element by indexing, and using the .field
operator
July 21, 2015
37
Structure Arrays
• Accessing Structure Elements
– Problematic if you make a typographical error:
July 21, 2015
38
Structure Arrays
• Accessing Structure Elements
– Should this happen, you can use the fieldnames(…) function
to determine the situation, and then the rmfield(…) function
to remove the offending entry
July 21, 2015
39
Structure Arrays
• Accessing Structure Elements
– Best to construct a complete structure and then insert it into
the structure array:
July 21, 2015
40
Structure Arrays
• Accessing Structure Elements
– If you insert that new CD beyond the end of the array, as one
might expect, MATLAB fills out the array with empty
structures:
July 21, 2015
41
Structure Arrays
• Manipulating Structures
– Structures and structure arrays can be manipulated in the
following ways:
– Single values can be changed using the “.” (dot) notation
directly with a field name:
>>cds(5).price = 19.95
– Or indirectly using the “.” (dot) notation with a variable the
field name:
>> fld = ‘price’;
>> cds(5).(fld) = 19.95
July 21, 2015
42
Structure Arrays
• Manipulating Structures
– Or by using MATLAB’s equivalent built-in functions:
• nms = fieldname(str) returns a cell array containing the names of the
fields in a structure or structure array
– >> flds = fieldnames(cds)
• if = isfield(str, <fildname> determines whether the given name is a
field in this structure or structure array
– >> if isfield(cds, ‘price’) …
• str = setfield(str. <fldname>, <value>) returns a new structure array
with the specified field set to the specfied value
– >> cds(1) = setfield(cds(1), …
–
‘price’, 19.95);
• Val = getfield(str, <fldname>) returns the value of the specified field
– >> disp(getfield(cds(1), ‘price’) );
July 21, 2015
43
Structure Arrays
• Manipulating Structures
– Or by using MATLAB’s equivalent built-in functions:
• Str = rmfield(str, <fldname>) returns a new structure array with the
specified field removed
– noprice = rmfield(cds, ‘price’);
– Values across the whole array can be retrieved using the “.”
notation by accumulating them into arrays; either into cell
arrays:
• >> title = {cds.title};
– Or if the values are all numeric, into a vector:
• >> prices = [cds.price];
– Exercise 7.5: The CD collection
– Smith text, page 171, bottom
– Note: after extracting the price values into a vector, all
normal vector operations – in this case, sum(…), can be
utilized
July 21, 2015
44
Engineering Example: Assembling a Structure
• Building a structure
• Problem here is how to decide the sequence in which
the components are delivered to the building site so
that components are available when needed, but not
piled up waiting to be used
• The construction needs to start from the fixed point A
shown in the figure on the following slide
• We need to analyze this information and compute the
order in which the components would be used to
assemble the structure
July 21, 2015
45
Engineering Example: Assembling a Structure
• Figure 7.1 from text:
July 21, 2015
46
Engineering Example: Assembling a Structure
• Data will be organized as a structure array with one
entry for each component
• One of the fields in that structure will be a cell array of
the names of the components to which this component
is connected
• Coding listings for this example follow on the next set
of slides
July 21, 2015
47
Engineering Example: Assembling a Structure
• Listing 7.6 Connectivity of a structure
July 21, 2015
48
Engineering Example: Assembling a Structure
• Listing 7.6 Connectivity of a structure
July 21, 2015
49
Engineering Example: Assembling a Structure
• Listing 7.7 Supporting Functions
July 21, 2015
50
Engineering Example: Assembling a Structure
• Listing 7.7 Supporting Functions
July 21, 2015
51
Engineering Example: Assembling a Structure
• Listing 7.7 Supporting Functions
July 21, 2015
52
Engineering Example: Assembling a Structure
• Listing 7.7 Supporting Functions
July 21, 2015
53
Engineering Example: Assembling a Structure
• Comments on example:
– The structure array is constructed using the beam(…)
function defined above
– We traverse the components to make a structure array,
FOUND, containing the components connected to the
current connection point, CONN
– We then go through the array FOUND, removing any
component already on the connected list and append the
names of those not removed to the connected list
– Function BEAM is used to determine whether a component
is connected to the component with the name provided
– Function ISON is used to determine whether a particular
string is on the connection list, a cell array of strings
July 21, 2015
54
Engineering Example: Assembling a Structure
• Comments on example:
– Function NEXTCONN is used to find the next connection to
use based on the latest component found-the “outer edges”
of the emerging structure-and its not being already on the
connected list
– If the component in question is not on the connected list, exit
and return it; note that the return variable, nm, has been set
in function NEXTCONN on lines 27-29
July 21, 2015
55