370 likes | 463 Vues
Learn about storing variables of different types in a single array using Cell Arrays and Structures. Understand arrays, matrices, multidimensional arrays, element-by-element arithmetic, and accessing elements in Cell Arrays. Explore creation, modification, and access techniques with practical examples. Discover the concept of Structures and how to use named fields to organize data effectively.
E N D
COMP 116: Introduction to Scientific Programming Lecture 25: Cell Arrays and Structures
Announcements and Reminders • Friday class will be taught by SachinPatil • This Wednesday’s quiz moved to Friday • This Wednesday office hours from 2-3pm • Midterm coming up
Today • How to store variables of different types (numbers, characters, strings, arrays, matrices) all in one single array? • Two options: • Cells • Structs
Data Structures • Arrays • Homogenous • Indexing by numbers • Cell Arrays • Heterogeneous • Indexing by numbers • Structures • Heterogeneous • Accessing by naming
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
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];
Most common 3D array • Images • 3 channels (red, green, blue) • Each channel is a 2D array
N-D Arrays: Arithmetic • Element-by-Element arithmetic • The same as before • + - .* ./ .\ .^ • Linear algebra (i.e., matrix) operations generally not used
Cell Arrays >> doc cell Under Help: MATLAB → Programming Fundamentals → Classes (Data Types) → Cell Arrays
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
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'}
Cell Arrays Note: Not the same concept as cells (%%) in publishable scripts
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
Accessing Cell Arrays: 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 % Change content some_guy{1,1} = 'Chuck' some_guy{2,2} = 1:5; some_guy{1,2} = []; % Delete content in cell 1,2 % Grab 1st, 2nd elements some_guy(1:2) row2 = some_guy (2,:) % Grab 2nd row of cells
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);
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.
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
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);
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}
Examples • Collection of strings • Extract important words from a document
Exercise • Write a function get_the_wordsthat • 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’}
Structures Under Help … MATLAB → Programming Fundamentals → Classes (Data Types) → Structures
Structures • Structures are a common concept in most programming languages • Each element inside a structure is given a unique name • These elements are called fields
Structures • Same example as before, but now with more data
Structures • Use named ‘fields’ for each variable alex.name = 'Alexander the Great'; alex.occupation = 'Conqueror'; alex.birth = 356; alex.fictional = false;
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);
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',...);
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
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;
Examples • Built-in structures • Figures get(gcf) • File lists >> files = dir files = 8x1 struct array with fields: name date bytes isdir datenum
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?
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;
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.
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 • {}, (), '.'
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.