Fondamenti di Informatica - Tor...

26
Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio [email protected]

Transcript of Fondamenti di Informatica - Tor...

Page 1: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

Fondamenti di Informatica

lesson 11

2012/04/26

Prof. Emiliano Casalicchio [email protected]

Page 2: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

Communication

  Class suspended on April 30 (next Monday)   May 7. Class will be held in “Aula 6”

2

Page 3: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

Agenda

  Questionnaire   Cell array and structures

3

Page 4: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-4

Objectives

Cell Arrays   Creating Cell Arrays   Accessing Cell Arrays   Using Cell Arrays   Processing Cell Arrays

MATLAB Structures   Constructing and Accessing One Structure   Constructor Functions

Structure Arrays   Constructing Structure Arrays   Accessing Structure Elements   Manipulating Structures

Engineering Example—Assembling a Structure

Page 5: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-5

7.1 Concept: Collecting Dissimilar Objects

Heterogeneous collections permit objects of different data types to be grouped in a collection.

  They allow data abstraction to apply to a much broader range of content.

  However, the fact that the contents of these collections may be of any data type severely restricts the operations that can be performed on the collections as a whole.

  Whereas a significant number of arithmetic and logical operations can be performed on whole number arrays, algorithms that process heterogeneous collections must deal with the data contents one item at a time.

Page 6: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-6

7.2 Cell Arrays

  Cell arrays, as the name suggests, have the general form of arrays and can be indexed numerically as arrays.

  However, each element of a cell array should be considered as a container in which one data object of any class can be stored.

  They can be treated as arrays of containers for the purpose of concatenation and slicing.

  However, if you wish to access or modify the contents of the containers, the cells must be accessed individually.

Page 7: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-7

Creating Cell Arrays

 By assigning values individually to a variable indexed with braces: >> A{1} = 42 A = [42]

 By assigning containers individually to a variable indexed with brackets:

>> B[1] = {[4 6]}; B = [1x2 double]

 By concatenating cell contents using braces {. . .}: >> C = {3, [1,2,3], 'abcde'} C = [3] [1x3 double] 'abcde'

 By concatenating cell containers: >> D = [A B C {'xyz'}] D = [42] [1x2 double] [3] [1x3 double] 'abcde' 'xyz'

Page 8: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-8

Accessing Cell Arrays

Continuing the previous examples, we have the following:

>> E = D(2) % parentheses - a container E = [4 6]

However, braces are used to access the contents of the containers as follows:

>> D{2} % braces - the contents ans = 4 6

If the right-hand side of an assignment statement results in multiple cell arrays, the assignment must be to the same number of variables. The built-in MATLAB function deal(...) is used to make these allocations.

Page 9: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-9

Using Cell Arrays

  Containing lists of possible values for switch/case statements

  Substituting for parameter lists in function calls   For example, suppose you have a function largest(a, b,

c) that consumes three variables and produces the largest of the three values provided. It can be used in the following styles: A = 4; B = 6; C = 5; N = largest(A, B, C) params = { 4, 6, 5 }; N = largest(params{1:3})

Page 10: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-10

Processing Cell Arrays

  The template for processing cell arrays is: <initialize result> for <index specification> <extract an element> <check the element accordingly> <process the element accordingly> end <finalize result>

  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 isa(item, 'class'),   iscell(...), ischar(...), islogical(...), isnumeric(...), and   isstruct(...)

Page 11: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

% Listing 7-2 - Cell array processing example

function ans = totalNums(ca) % count the numbers in a cell array ans = 0 ; for in = 1 :length(ca) item = ca{in} ; % extract the item if isnumeric(item) % check if a vector ans = ans + prod(size(item)); end end

11

Page 12: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-12

7.3 MATLAB Structures

  Structures allow items in the collection to be indexed by field name.   The data contained in a structure is referenced by field name, e.g.,

item1.   The rules for making a field name are the same as those for a variable.   Fields of a structure, like the elements of a cell array, are

heterogeneous—they can contain any MATLAB object.

Page 13: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-13

Constructing and Accessing One Structure

  To set the value of items in a structure A, the syntax is as follows:

>> A.item1 = 'abcde' A = item1: 'abcde' >> A.item2 = 42 A = item1: 'abcde' item2: 42

  Fields in a structure are accessed in the same way—by using the dotted notation.

>> A.item2 = A.item2 ./ 2 A = item1: 'abcde' item2: 21

Page 14: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-14

Manipulating Field Names

  To determine the names of the fields in a structure, the built-in function fieldnames(...) returns a cell array containing the field names as strings.

>> names = fieldnames(A) names = 'item1' 'item2'

  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:

>> fn = names{1}; >> A.(fn) = [A.(fn) 'fg'] A = item1: 'abcdefg' item2: 21

Page 15: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-15

More about Field Names

  You can remove a field from a structure using the built-in function rmfield(...).

  Be careful. rmfield(...) returns a new structure with the requested field removed. It does not remove that field from your original structure.

  If you want the field removed from the original, you must assign the result from rmfield(...) to replace the original structure:

>> A = rmfield(A, 'item1') A = item2: 21

Page 16: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-16

Why Constructor Functions?

Use constructor functions, as opposed to “manually” entering data into structures, for the following reasons:

 Manual entry can result in strange behavior due to typographical errors or having fields in the wrong order

 The resulting code is generally more compact and easier to understand

 When constructing collections of structures, it enforces consistency across the collections

Page 17: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-17

Built-in Constructor Function struct(…)

>> struct('first','Fred', ... 'last','Jones', ... 'phone','(123) 555-1212', ...

'birth', struct( 'day', 31, ... 'month', 'February', ... 'year', 1965 )) ans = first: 'Fred' last: 'Jones'

phone: '(123) 555-1212' birth: [1x1 struct]

Page 18: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-18

Custom Constructor Functions

  A typical custom constructor function function ans = makeCD(gn, ar, ti, yr, st, pr) % integrate CD data into a structure ans.genre = gn ; ans.artist = ar ; ans.title = ti; ans.year = yr; ans.stars = st; ans.price = pr;

  Usage: >> CD = makeCD('Blues', 'Charles, Ray', & 'Genius Loves Company', 2004, 4.5, 15.35 ) CD = genre: 'Blues' artist: 'Charles, Ray' title: 'Genius Loves Company' year: 2004 stars: 4.5000 price: 15.3500

Page 19: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-19

Building Structure Arrays Manually

>> entry(1).first = 'Fred'; >> entry(1).last = 'Jones'; >> entry(1).age = 37; >> entry(1).phone = ' (123) 555-1212'; >> entry(2).first = 'Sally’; >> entry(2).last = 'Smith’; >> entry(2).age = 29; >> entry(2).phone = '(000) 555-1212' entry = 1x2 structure array with fields: first last age phone

Page 20: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-20

Building Structure Arrays with struct(…)

genres = {'Blues', 'Classical', 'Country' }; artists = {'Clapton, Eric', 'Bocelli, Andrea', … 'Twain, Shania' }; years = { 2004, 2004, 2004 }; stars = { 2, 4.6, 3.9 }; prices = { 18.95, 14.89, 13.49 }; cds = struct( ‘genre’, genres, … 'artist', artists, … 'year', years, … 'stars', stars, … 'price', prices);

Page 21: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-21

Building Structure Arrays with makeCD(…) cds(1) = makeCD('Blues', 'Clapton, Eric', ... 'Sessions For Robert J', 2004, 2, 18.95 ) cds(2) = makeCD('Classical', ... 'Bocelli, Andrea', 'Andrea', 2004, 4.6, 14.89 ) cds(3) = makeCD( 'Country', 'Twain, Shania', ... 'Greatest Hits', 2004, 3.9, 13.49 ) cds(4) = makeCD( 'Latin', 'Trevi, Gloria', ... 'Como Nace El Universo', 2004, 5, 12.15 ) cds(5) = makeCD( 'Rock/Pop', 'Ludacris', ... 'The Red Light District', 2004, 4, 13.49 ) cds(6) = makeCD( 'R & B', '2Pac', ... 'Loyal To The Game', 2004, 3.9, 13.49 ) cds(7) = makeCD( 'Rap', 'Eminem', ... 'Encore', 2004, 3.5, 15.75 ) cds(8) = makeCD( 'Heavy Metal', 'Rammstein', ... 'Reise, Reise', 2004, 4.2, 12.65 )

Page 22: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-22

7.5 Engineering Example—Assembling a Structure

  Given this structure, determine the order of assembly starting from A.

Page 23: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-23

Assembly Description

data(1) = beam('A-1', 0.866, 0.5, {'A','A-2','A-3','D-1'} ); data(2) = beam('A-2', 0, 1, {'A','A-3','B-1','B-2’} ); data(3) = beam('A-3', 0.866, 1.5, {'A-1','A-2','B-1','D-1'} ); data(4) = beam('B-1', 0.866, 2.5,

{'A-2','A-3','B-2','B-3','D-1','D-2'} ); data(5) = beam('B-2', 0, 3, {'A-2','A-3','B-1','B-3','C-1','C-2'} ); data(6) = beam('B-3', 0.866, 3.5,{'B-1','B-2','C-1','C-2','D-1','D-2'} ); data(7) = beam('C-1', 0.866, 4.5, {'B-2','B-3','C-2','C-3','D-2'} ); data(8) = beam('C-2', 0, 5, {'B-2','B-3','C-1','C-3','C'} ); data(9) = beam('C-3', 0.866, 5.5, {'C-1','C-2','D-2','C'} ); data(10) = beam('D-1', 1.732, 2, {'A-1','A-3','B-1','B-3','D-2'} ); data(11) = beam(‘D-2’, 1.732, 4, {'B-1','B-3','C-1','C-3','D-1'} )

% Listing 7-7 - Support functions function ans = beam( nm, xp, yp, conn ) % construct a beam structure with fields: % name - beam name % xp, yp - coordinates of its centroid % conn - cell array - names of adjacent beams % useage: ans = beam( nm, xp, yp, conn ) ans.name = nm; ans.pos = [xp, yp]; ans.connect = conn;

Page 24: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-24

Solution

conn = 'A'; clist = {conn}; while true index = 0; % find all the beams % connected to conn for in = 1:length(data) str = data(in); if touches(str, conn) index = index + 1; found(index) = str; end end % continua

% Listing 7-7 - Support functions function res = touches(beam, conn)% does the beam touch this connecting point?% usage: res = touches(beam, conn) res = false; for in = 1:length(beam.connect) item = beam.connect{in}; if strcmp(item,conn) res = true; break; end end

% an example content of our struct array

%beam(‘D-2’, 1.732, 4, {'B-1','B-3','C-1','C-3','D-1'} )

Page 25: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

% Listing 7-7 - Support functions function nm = nextconn( fnd, cl )% find a connection name among % those found not already connected% usage: nm = nextconn( fnd, cl ) for in = 1:length(fnd) item = fnd(in); cn = item.connect; for jn = 1:length(cn) nm = cn{jn}; if ~ison(nm, cl) break; end end end function res = ison( nm, cl ) % is this beam on the connection list, % a cell array of beam names % usage: res = ison( beam, cl ) res = false; for in = 1:length(cl) item = cl{in}; if strcmp(item, nm) res = true; break; end end

1-25

Solution (continued)

% eliminate those already % connected for jn = index:-1:1 if ison(found(jn).name, clist) found(jn) = []; else clist = [clist found(jn).name}]; end end if length(found) > 0 conn = nextconn( found, clist ); else break; end end %end while disp('the order of assembly is:') disp(clist)

Page 26: Fondamenti di Informatica - Tor Vergatadidattica.uniroma2.it/assets/uploads/corsi/141767/Lezione11-FOI.pdf · Fondamenti di Informatica lesson 11 2012/04/26 Prof. Emiliano Casalicchio

1-26

Summary

■ Cell arrays are vectors of containers; their elements can be manipulated either as vectors of containers, or individually by inserting or extracting the contents of the container using braces in place of parentheses. ■ The elements of a structure are accessed by name rather than by indexing, using the dot operator to specify the field name to be used. ■ Structures can be collected into structure arrays whose elements are structures all with the same field names. These elements can then be indexed and manipulated in the same manner as the cells in a cell array.