lec 15 oct 27 more examples of recursive programs more about cell arrays structures in matlab

28
Lec 15 Oct 27 • more examples of recursive programs • more about cell arrays • structures in Matlab

Post on 21-Dec-2015

252 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

Lec 15 Oct 27

• more examples of recursive programs

• more about cell arrays

• structures in Matlab

Page 2: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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>

Page 3: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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 isa(item, 'class'),

– iscell(...), ischar(...), islogical(...), isnumeric(...), and

– isstruct(...)

Page 4: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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 5: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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 = 42A =item1: 'abcde'item2: 42

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

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

Page 6: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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 7: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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 8: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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 9: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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 10: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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: 2004stars: 4.5000price: 15.3500

Page 11: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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:firstlastagephone

Page 12: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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 13: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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 14: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

14

Binary search tree – a recursive structure

Recursively defined structures can be useful in some applications.

Define a binary search tree as a struct with three fields:

key – a real number left, right – binary search trees.

base case: empty tree (represented by empty cell)

Ex: { 12, { 8, {}, {} }, { 7, { 9, {}, {}}, { 4, {}, {} } } }

Page 15: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

Binary Search Trees (BST)• A data structure for efficient searching,

inser-tion and deletion (dictionary operations)

• Binary search tree property• For every node x:• All the keys in its left

subtree are smaller than the key value in x

• All the keys in its right subtree are larger than the key value in x

Page 16: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

Binary Search Trees

A binary search tree

Not a binary search tree

Example:

Tree height = 4

Key requirement of a BST: all the keys in a BST are distinct, no duplication

Page 17: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

Binary Search Trees

The same set of keys may have different BSTs

Page 18: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

Searching BST

Example: Suppose T is the tree being searched:• If we are searching for 15, then we are done.• If we are searching for a key < 15, then we

should search in the left subtree.• If we are searching for a key > 15, then we

should search in the right subtree.

Page 19: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab
Page 20: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

Search • Find X: return true (false) if x is in tree T.

function out = search(T, x)if isempty(T) out = false; return;elseif abs(T.key – x) < 0.0001 out = true; return;elseif T.key > x out = search(T.left, x);else out = search(T.right, x);end;

Page 21: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

Inorder Traversal of BST• Inorder traversal of BST prints out all the keys in

sorted order

Inorder: 2, 3, 4, 6, 7, 9, 13, 15, 17, 18, 20

treePrint(T.left);Print(T.key);treePrint(T.right);

Page 22: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

findMin/ findMax Goal: return the node containing the smallest

(largest) key in the tree

Algorithm: Start at the root and go left (right) as long as there is a left (right) child. The stopping point is the smallest (largest) element

Page 23: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

InsertionTo insert(X): Proceed down the tree as you would for search. If x is found, do nothing (or update some

secondary record) Otherwise, insert X at the last spot on the path

traversed

X = 13

Page 24: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

Another example of insertion

Example: insert(11). Show the path taken and the position at which 11 is inserted.

Note: There is a unique place where a new key can be inserted.

Page 25: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

25

Binary Search Trees / Slide 25

Insertion

X = 13

function out = insert(A, x)if isempty(A) out.key = x; out.left = {}; out.right = {};elseif A.key < x A.right = insert(A.right, x); out = A;else A.left = insert(A.left, x); out = A;end;

Page 26: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

Recursive backtracking – project

The next problem introduces a general technique of problem solving that can be used in a wide range of settings. We will use it to solve the following problem: a Latin square of order n is a n by n square matrix in which each row and each column contains exactly one occurrence of numbers 1 to n. (In mid-term, you wrote a program to test if a given matrix is a Latin square.)

Our problem is more complicated – given a partially filled Latin square, we want to complete it into a Latin square, if possible.

Page 27: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

Test case – a simple example

Page 28: Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab

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.