Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 116: Introduction to Scientific Programming Lecture 25: Cell Arrays and Structures.

Similar presentations


Presentation on theme: "COMP 116: Introduction to Scientific Programming Lecture 25: Cell Arrays and Structures."— Presentation transcript:

1 COMP 116: Introduction to Scientific Programming Lecture 25: Cell Arrays and Structures

2 Announcements and Reminders Friday class will be taught by Sachin Patil This Wednesday’s quiz moved to Friday This Wednesday office hours from 2-3pm Midterm coming up

3 Today How to store variables of different types (numbers, characters, strings, arrays, matrices) all in one single array? Two options: ◦ Cells ◦ Structs

4 Data Structures Arrays ◦ Homogenous ◦ Indexing by numbers Cell Arrays ◦ Heterogeneous ◦ Indexing by numbers Structures ◦ Heterogeneous ◦ Accessing by naming

5 REVIEW: ARRAYS

6 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

7 N-D arrays 3 -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];

8 Most common 3D array Images ◦ 3 channels (red, green, blue) ◦ Each channel is a 2D array

9 Most common 3D array

10 N-D Arrays: Arithmetic Element-by-Element arithmetic ◦ The same as before ◦ + -.*./.\.^ Linear algebra (i.e., matrix) operations generally not used

11 CELL ARRAYS >> doc cell Under Help: MATLAB → Programming Fundamentals → Classes (Data Types) → Cell Arrays

12 Creating Cell Arrays Just 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

13 Creating Cell Arrays Just 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'}

14 Cell Arrays ArraysCell 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

15 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

16 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 1 st, 2 nd elements some_guy(1:2) row2 = some_guy (2,:) % Grab 2 nd 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

17 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);

18 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.

19 Useful Commands celldisp – shows contents of the cell in the command winow, one element at a time cellplot – graphical display of all cells in a cell array

20 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);

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

22 Examples Collection of strings ◦ Extract important words from a document

23 Exercise Write 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’}

24 STRUCTURES Under Help … MATLAB → Programming Fundamentals → Classes (Data Types) → Structures

25 Structures StructuresCell 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

26 Structures Same example as before, but now with more data NameOccupationBirthFictional Alexander the GreatConqueror356 BCNo Winnie the PoohBear1926Yes Jack the RipperSerial Killer1800sNo Stephen the ColbertPolitical Pundit1964Hmm

27 Structures Use named ‘fields’ for each variable alex.name = 'Alexander the Great'; alex.occupation = 'Conqueror'; alex.birth = 356; alex.fictional = false;

28 Structures Use 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);

29 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',...);

30 Structure Arrays One way to initialize is to use a ‘template’ % create structure layout % note the use of default values and empty arrays template = 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

31 Examples Nested 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 array class.building = 'FB'; class.room = 7;

32 Examples Built-in structures ◦ Figures get(gcf) ◦ File lists >> files = dir files = 8x1 struct array with fields: name date bytes isdir datenum

33 Examples The 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?

34 Common Pitfalls Remember 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;

35 Style Guidelines Use 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.

36 Summary Review 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  {}, (), '.'

37 Useful functions rmfield – removes a field from a structure isstruct – tests whether a variable is of type structure isfield – tests whether a name string is a field in the specified structure. fieldnames – returns names of all fields in a struture.


Download ppt "COMP 116: Introduction to Scientific Programming Lecture 25: Cell Arrays and Structures."

Similar presentations


Ads by Google