comp 116: introduction to scientific programming lecture 11: functions

33
COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Upload: lindsay-summers

Post on 04-Jan-2016

222 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

COMP 116: Introduction to Scientific Programming

Lecture 11: Functions

Page 2: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

So farScript files

◦ All code inside one big file◦Perhaps structured into cells

Used built-in matlab functions◦sin, cos, zeros etc.

How do we structure more complex code?

How do we write our own functions?

Page 3: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Calling FunctionsHow does MATLAB call its own functions?

Matlab loads it’s own function files and runs them through the interpreter◦ Input variables map onto function inputs◦Function outputs get stored in specified

variables

% MyScript.mx = [4 3 9 2 9 1 2 7 4];maxX = max(x);......

max.minput

output

Page 4: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Calling FunctionsHow does MATLAB call its own

functions?

In MATLAB, each function should go into a separate m-file

% MyScript.mx = [4 3 9 2 9 1 2 7 4];maxX = max(x);......

max.minput

output

Page 5: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Syntax vs. SemanticsWhat is syntax?

◦Grammar◦Rules that let you write in the language◦Punctuation, etc.

Why do we need syntax rules?

◦ Syntax rules allow compilers and interpreters to correctly convert our source code into something the computer understands.

Page 6: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

SemanticsWhat are semantics?

◦Meaning◦What does your function actually do?◦What problem(s) does it solve?

Page 7: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Writing a function: Syntax

function [outputs] = funcName( inputs )% Function Comments… % Body (implementation)end %optional

Note: The name of the function and the name of the m-file should be the same

Page 8: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Function Syntax

Must start with function keyword◦Otherwise, it’s a script

Page 9: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Function Syntax

Function name◦ Again: remember that this must be the same as

the name of the m-file

Page 10: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Function Syntax

Function return values/output◦ Potentially multiple values may be returned from the function◦ [r, c] = size(A)

Page 11: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Function Syntax

Function input values/parameters◦ Potentially multiple arguments may be passed into a function◦ s = sum(A, 2)

Page 12: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Function SyntaxComment block, just below the first line

◦Searched by lookfor◦Displayed when you type help

Page 13: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Function implementation◦Where you do all the ‘work’◦Has comments, expression, function calls…

Function Syntax

Page 14: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

JargonParameters

◦ The variables declared in the function interfaceArguments

◦ The actual values supplied when the function is called.

These are function parameters

When calling the function: c = DiceToss(num_throws, desired_value);

These are function arguments

Page 15: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

A summary of function rules

Most important: function name and its corresponding .m file name should match.

Functions can have several inputs◦ common in most languages

Functions can also have several outputs◦ This is different from most other languages.

Input and output are optional

Comments are optional◦ But a good programming practice

Page 16: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

More rules …One function per file

◦Exception: helper functions Meant to only be used internally by the

main functionfunction [avg, med] = newstats(u)% NEWSTATS Find mean w/ subfuctions. n = length(u); avg = helper_mean(u, n);

function a = helper_mean(v, n) % Subfunction: calculate average. a = sum(v)/n;

All in a single m file

Page 17: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

More rules …

Function Names are case sensitive◦DiceToss is different from dicetoss is

different from diceToss…

Page 18: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

More rules …function [avg, med] = newstats(u)% NEWSTATS Find mean w/ subfuctions. n = length(u); avg = helper_mean(u, n);

function a = helper_mean(v, n) % Subfunction: calculate average. a = sum(v)/n;

Page 19: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

More rules …

Gotcha: you can accidently hide system functions, constants, and workspace variables by creating your own function with the exact same name.

function [avg, med] = newstats(u)% NEWSTATS Find mean w/ subfuctions. n = length(u); avg = mean(u, n);

function a = mean(v, n) % Subfunction: calculate average. a = sum(v)/n;

Page 20: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

More rules …

Be careful with parentheses: [] vs ()

◦[r, c] = size(A)◦(r, c) = size(A) ◦[r, c] = size[A]

Think: ◦Difference between

myfunc([1, 2, 3]) and myfunc(1, 2, 3)

Incorrect

Page 21: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Function examplesMultiple inputs

No inputs

Multiple outputs

No outputs

Page 22: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Exercise 1Write an absolute value function

◦Assume the input is just a scalar

Convert your guess-the-number script to a function◦What is the input?◦What is the output?

Page 23: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

ScopeFunctions run in their own

‘workspaces’

MATLAB

sq.m x =4 x2 =16

foo =4 x2 =5 bar =16

Page 24: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Scope: Global Variables (Workspace)Global MATLAB workspace

◦Variables belonging to script files and command window

Workspace Variables◦come into existence after they are created

by assignment.◦exist until MATLAB quits or clear command

is used on variables to remove them.◦Accessible from command window and

scripts◦NOT accessible from inside functions

Page 25: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Scope: Local Variables (Functions)Function workspaces

◦Local scope

Variables◦Parameter variables live from function entry◦Local variables live from assignment◦Until function finishes (or clear)◦Local workspace is cleared at end of

function◦Output copied/assigned to variables in

calling workspace

Page 26: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Scripts vs. Functions

Page 27: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Why use Functions?

Top-down designEncapsulationMore flexible, resuable codeTesting strategy

Page 28: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Top-down design

Break a complex problem into simpler manageable problems

Solve simpler problems

Connect simple solutions to solve original problem

Functions give your code structure

Page 29: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Encapsulation

A function is isolated from the rest of the system, and interacts only through its input and output arguments.◦A function can't mess up the variables in

your workspace◦Likewise, you can't mess up a function

by changing values

Much more powerful, and fewer ‘side-effects’ than scripts

Page 30: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Flexible, reusable code

A script only solves one instance of a problem

A function can solve all instances◦You can call hypotenuse with any values of a and b

Since functions are encapsulated, this means you only need to know its interface (what it does), not its implementation (how it does it)

Share your solution to a problem with others.Collaboration

◦Team, organization, world

Page 31: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Easier testing

If you write your program as a 500-line script, and it gives the wrong answer. . .◦Good luck with that!

If you write your program as a small function that calls other functions that call other functions. . .◦Test the simplest functions first◦Check that functions are connected

correctly

Page 32: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Variable number of inputsHow does a function like min() work?

◦ It can take a variable number of inputs min(x); min(x, 1) min(x, [], 1)

varargin, nargin◦varargin is a cell array – we’ll talk about cell

arrays later◦The variable nargin is automatically set in the

local workspace of each function, and tells you how many input variables were actually supplied to the function.

Page 33: COMP 116: Introduction to Scientific Programming Lecture 11: Functions

Variable number of outputsHow does size() work?

◦Can return variable number of outputs

varargout, nargout◦nargout returns the number of

output arguments specified for a function.