comp 116: introduction to scientific programming lecture 25: cell arrays and structures

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

Upload: milo-potter

Post on 25-Dec-2015

224 views

Category:

Documents


0 download

TRANSCRIPT

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

COMP 116: Introduction to Scientific Programming

Lecture 25: Cell Arrays and Structures

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

Announcements and RemindersFriday class will be taught by

Sachin Patil

This Wednesday’s quiz moved to Friday

This Wednesday office hours from 2-3pm

Midterm coming up

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

Today

How to store variables of different types (numbers, characters, strings, arrays, matrices) all in one single array?

Two options: ◦Cells◦Structs

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

Data Structures

Arrays◦Homogenous◦Indexing by numbers

Cell Arrays◦Heterogeneous◦Indexing by numbers

Structures◦Heterogeneous◦Accessing by naming

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

REVIEW: ARRAYS

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

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

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

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

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

Most common 3D array

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

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

Most common 3D array

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

N-D Arrays: ArithmeticElement-by-Element arithmetic

◦The same as before ◦+ - .* ./ .\ .^

Linear algebra (i.e., matrix) operations generally not used

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

CELL ARRAYS

>> doc cell

Under Help:MATLAB → Programming Fundamentals → Classes (Data Types) → Cell Arrays

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

Creating Cell ArraysJust 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

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

Creating Cell ArraysJust 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'}

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

Cell Arrays

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

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

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

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

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 1st, 2nd elements

some_guy(1:2)

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

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

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

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

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.

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

Useful Commandscelldisp – shows contents of the

cell in the command winow, one element at a time

cellplot – graphical display of all cells in a cell array

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

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

0

4

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

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}

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

ExamplesCollection of strings

◦Extract important words from a document

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

ExerciseWrite 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’}

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

STRUCTURES

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

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

Structures

Structures Cell 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

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

StructuresSame example as before, but now

with more data

Name Occupation Birth Fictional

Alexander the Great

Conqueror 356 BC No

Winnie the Pooh Bear 1926 Yes

Jack the Ripper Serial Killer 1800s No

Stephen the Colbert

Political Pundit

1964 Hmm

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

StructuresUse named ‘fields’ for each

variablealex.name = 'Alexander the Great';alex.occupation = 'Conqueror';alex.birth = 356;alex.fictional = false;

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

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

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

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

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

Structure ArraysOne way to initialize is to use a

‘template’% create structure layout% note the use of default values and empty arraystemplate = 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

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

ExamplesNested 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 arrayclass.building = 'FB';class.room = 7;

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

ExamplesBuilt-in structures

◦Figures

get(gcf) ◦File lists

>> files = dirfiles = 8x1 struct array with fields: name date bytes isdir datenum

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

ExamplesThe 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?

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

Common PitfallsRemember 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;

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

Style GuidelinesUse 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.

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

SummaryReview 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

{}, (), '.'

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

Useful functionsrmfield – removes a field from a

structureisstruct – tests whether a

variable is of type structureisfield – tests whether a name

string is a field in the specified structure.

fieldnames – returns names of all fields in a struture.