Lec 13 Oct 20 cell arrays (Chapter 4) structures (Chapter 4) generating subsets generating permutations (HW 4 problem)

Slides:



Advertisements
Similar presentations
Chapter 10 Introduction to Arrays
Advertisements

CMPS 1371 Introduction to Computing for Engineers STRUCTURE ARRAYS.
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
Lecture 4 Sept 8 Complete Chapter 3 exercises Chapter 4.
Programming with Collections Collections in Java Using Arrays Week 9.
Lecture 12 Oct 15 Recursion – more examples Chapter 8 problems and solutions Cell arrays, Chapter 10.
Lec 13 Oct 17 cell arrays structures advanced recursive programs.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Lec 15 Oct 27 more examples of recursive programs more about cell arrays structures in Matlab.
Cells and Structures Array Cells and Array Structures.
Computer Science II Exam I Review Monday, February 6, 2006.
Concatenation MATLAB lets you construct a new vector by concatenating other vectors: – A = [B C D... X Y Z] where the individual items in the brackets.
Lecture 18 Oct 24 Cell arrays (Ch 4), structures recursion (Ch 12)
Lecture 4 Sept 7 Chapter 4. Chapter 4 – arrays, collections and indexing This chapter discusses the basic calculations involving rectangular collections.
Testing a program Remove syntax and link errors: Look at compiler comments where errors occurred and check program around these lines Run time errors:
 Pearson Education, Inc. All rights reserved Arrays.
Lec 14 Oct 22 more examples of recursive programs more about cell arrays structures in Matlab.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Engineering Computation with MATLAB Second Edition by David M. Smith.
Lists in Python.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Input, Output, and Processing
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
CHAPTER: 12. Array is a collection of variables of the same data type that are referenced by a common name. An Array of 10 Elements of type double.
Lecture 15 Chapters 6 and 7. Outline from Chapter Character String Concepts: Mapping and Casting 6.2 MATLAB Implementation Slicing and Concatenating.
1. Exam Topics Difference between computers and calculators John creates a new device. It will compute the orbit of all the planets in the solar system.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Built-in Data Structures in Python An Introduction.
Collection Classes Eric Roberts CS 106B January 14, 2013 (Part 1: Vectors, Grids, Stacks, and Queues)
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Overview of C. C—a high-level programming language developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories. We will discuss: –the elements of a.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
Covenant College December 18, Laura Broussard, Ph.D. Visiting Professor COS 131: Computing for Engineers Chapter 7: Cell Arrays and Structures.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Lecture 13 Oct 15, 2012 cell array (review) Ch 4 recursion (Ch 12)
The ArrayList Data Structure The Most Important Things to Review.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Introduction to programming in java Lecture 21 Arrays – Part 1.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Department of Computer Science,
Java Review: Reference Types
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
String Manipulation Chapter 7 Attaway MATLAB 4E.
Dynamic Data Structures and Generics
Chapter 8 Data Structures: Cell Arrays and Structures
Fondamenti di informatica structures
MSIS 655 Advanced Business Applications Programming
Chapter 8 Data Structures: Cell Arrays and Structures, Sorting
Presentation transcript:

Lec 13 Oct 20 cell arrays (Chapter 4) structures (Chapter 4) generating subsets generating permutations (HW 4 problem)

Cell arrays suppose we want to represent a collection of sets such as: {1, 2, 4}, {3, 4, 6}, {7, 8} Each set can be represented by vector: [1, 2, 4], [3, 4, 6], [7, 8] >> A = [[ 1, 2, 4], [3, 4, 6], [7, 8]] A becomes [1, 2, 4, 3, 4, 6, 7, 8]

Cell arrays

Cell array – examples

Cell – operations

More about cell arrays and struct arrays 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

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.

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.

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'

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.

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})

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(...)

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.

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

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

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

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

Built-in Constructor Function struct(…) >> struct('first','Fred',... 'last','Jones',... 'phone','(123) ',... 'birth', struct( 'day', 31,... 'month', 'February',... 'year', 1965 )) ans = first: 'Fred' last: 'Jones' phone: '(123) ' birth: [1x1 struct]

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, ) CD = genre: 'Blues' artist: 'Charles, Ray' title: 'Genius Loves Company' year: 2004 stars: price:

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

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, }; cds = struct( ‘genre’, genres, … 'artist', artists, … 'year', years, … 'stars', stars, … 'price', prices);

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

Project: Generating all subsets of a given set Given a set, like [1, 3, 4], the subsets are: [ ] [1] [3] [4] [1 3] [1 4] [3 4] [1 3 4] We want to write a program to generate all the subsets of a given collection

Idea behind algorithm – recursion This is a problem for which non-recursive solutions are significantly harder than recursive solutions. Idea: input array is a of length n. Recursively find all subsets of a(2:n) Then add a(1) to each of the subsets. Combine the two collections.

Since we need to represent a collection of sets, we have two choices: 1. use of cell arrays 2. use of two-dimensional arrays The latter is not suitable for this problem since the sizes of the subsets are not the same We use recursion to generate the solution. We need a function insert that inserts a given number into all the sets of a given collection.

Example showing how insert works

Code for insert function out = insert(i, lst) % inserts i into each membet of lst for j = 1:length(lst) out{j}= [i, lst{j}]; end;

Code for subsets function L = subsets(lst) % generates all subsets of lst if length(lst) == 0 L = {[]}; elseif length(lst) == 1 L = {[lst(1)],[]}; else L1 = subsets(lst(2:end)); L2 = insert(lst(1), L1); L = [L1, L2]; end;

Printing the contents of a cell array function setprint(cellset) % prints every member of the cell in one line % assume cellset is a collection of sets of integers for k=1:length(cellset) aprint(cellset{k}); fprintf('\n'); end; function aprint(r) for j = 1:length(r) fprintf('%d', r(j)); fprintf(' '); end; fprintf('\n')

Generating all permutations of a given set Example: set [ 1 3 4] Permutations: [1 3 4] [1 4 3] [3 1 4] [3 4 1] [4 1 3] [4 3 1]