comp 116: introduction to scientific programming lecture 37: final review

26
COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Upload: emmeline-jonas

Post on 14-Dec-2015

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

COMP 116: Introduction to Scientific Programming

Lecture 37: Final Review

Page 2: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Functions

Page 3: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Writing Simple functionfunction [o1, o2]=funcName( i1, i2 )% Function Comments… % Body (implementation)end %optional

• Can have multiple inputs (i1) and multiple outputs (o2)

function [] = funcName()function o1 = funcName()function o1 = funcName( i1 )function o1 = funcName( i1, i2 )function [o1, o2] = funcName( i1, i2, i3)

Page 4: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

WorkspaceGlobal vs. Local StorageGlobal Workspace

◦Shared by Command Window and script commands

Local Workspace◦Created locally on entry to each

function◦Disappears on exit from function call.

% This is a scriptradius = 10;area = pi .* radius .^2;

function [area] = circ_area(radius)area = pi .* radius .^ 2;

% Call function in workspacemy_area = circ_area( 10 );

Page 5: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Looping

Page 6: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Loops: for loop statementthe counted loop solution

for <varindex> = <start>:<stop><Body: do some work>

end

for <idx> = <start>:<step>:<stop><Body: do some work>

end

Page 7: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Examples: Find sum

function ret=my_sum(A)% find minimum in the vector Aret=0;for i=1:length(A) ret=ret+A(i);endend

Find minimum will be very similar

Page 8: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Examples: Find the first occurrence of k in an array

function elem=find_first(A,k)elem=0;for i=1:length(A) if (A(i)==k)

elem=i; break; endend

Page 9: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

ExercisesFind the minimum value in a

matrix

Given an array, check if any two elements of the array sum to zero

Page 10: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Loops: while loop statementthe conditional loop solution

while <test> <Body: do some work> <Update: make progress towards exiting loop>end• While loops are great if we don’t know how many times

we need to loop, but if we can write a test for when we’re done

• For this to work properly, the test needs to evaluate to a logical value

• The while loop will run as long as test evaluates to true

• The while loop does not have a built-in counter like the for-loop (if you want to count something, you need to implement the counter yourself)

Page 11: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Example: Golden RatioGolden ratio is the solution of x^2-x-1=0For any positive number x, sqrt(x+1) is a

better approximation of golden ration than x. Use this rule in a while loop to find the some x such that abs(x^2-x-1) is less than 0.000001

eps=0.000001; x=100; while abs(x^2-x-1) > eps x=sqrt(x+1); end

Page 12: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Strings

Page 13: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Strings as a vector of charsCan be manipulated like any other

vector

s1 = 'The quick brown fox 's2 = 'jumped over the lazy dog'

s = [s1, s2] % concatenate stringss(5) % ans = qs(17:19) % ans = foxjIdx = find( s == 'j' )jStr = s(jIdx:jIdx+3) % ans = jump

Page 14: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

String Comparison

Avoid normal comparison operators!◦s1 == s2, s1 < s3, s1 >= s3◦Operators work element by element (on

characters)◦Thus, strings (i.e., the vector of chars) must

be same length

Use string comparison functions instead◦strcmp(), string comparison◦strcmpi, string comparison while ignoring

case◦strncmp, strncmpi:

Similar, but compares first n characters only

Page 15: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

String Searching

strfind◦Search for a string inside another

string◦returns indices to start of each

instancestrVal = [‘with great power comes great responsibility.’];

strfind( strVal, ‘great’)

% ans = [6 24]

Page 16: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

String Replacement

strrep

strVal = [‘with great power comes great responsibility.’];

strrep( strVal, ‘great’, ‘no’)

Page 17: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Cell Arrays and Structures

Page 18: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Cell Arrays vs. ArraysArray Cell Array• Element accessed by index/indices• Elements all need to be of the same type

• Elements accessed by index/indices• Elements can have distinct types

Basically, think of cell arrays as being more flexible data structures than the ‘standard’ arrays.

Page 19: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Accessing Cell Arrays Crucial distinction between {} and ()

operators

Example:A = { false, rand(3); 4.0, ‘This is a string’ };

A{1} or A{1,1} extracts the logical value false A(2) or A(2,1) extracts a 1x1 cell-array containing 4.0 A(2,:) extracts a 1x2 cell-array containing the bottom row A{:,2} extracts the values of the second column as

separate entities; use: [a,b] = A{:,2} for proper assignment

Indices work just as for ‘standard’ arrays.

Page 20: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Cell Arrays vs. StructuresStructure Cell Array• Element accessed by name• Elements can have distinct types

• Elements accessed by index/indices• Elements can have distinct types

Structures are very convenient data types when storingInformation belonging to one organizational unit, e.g.,

NameAge Date of BirthHeightWeight…

Page 21: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

StructuresUse named ‘fields’ for each

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

Page 22: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

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 23: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

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 24: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

File I/O

Page 25: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Useful stuffOpening a file:

◦ help fopen◦ Open in read, write or append mode◦ Always close your open files with fclose

Text files:◦ Writing: fprintf◦ Reading: fgetl

MATLAB data files:◦ Writing: save◦ Reading: load

Other useful notes

feof: test of end of file

fprintf: use ‘%d’, ‘%f’, etc.

fgetl: get a line from a (text) file

Page 26: COMP 116: Introduction to Scientific Programming Lecture 37: Final Review

Good luck!