COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
-
Upload
lindsay-summers -
Category
Documents
-
view
221 -
download
1
Transcript of COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
![Page 1: COMP 116: Introduction to Scientific Programming Lecture 11: Functions.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/1.jpg)
COMP 116: Introduction to Scientific Programming
Lecture 11: Functions
![Page 2: COMP 116: Introduction to Scientific Programming Lecture 11: Functions.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/2.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/3.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/4.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/5.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/6.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/7.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/8.jpg)
Function Syntax
Must start with function keyword◦Otherwise, it’s a script
![Page 9: COMP 116: Introduction to Scientific Programming Lecture 11: Functions.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/9.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/10.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/11.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/12.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/13.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/14.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/15.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/16.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/17.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/18.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/19.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/20.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/21.jpg)
Function examplesMultiple inputs
No inputs
Multiple outputs
No outputs
![Page 22: COMP 116: Introduction to Scientific Programming Lecture 11: Functions.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/22.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/23.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/24.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/25.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/26.jpg)
Scripts vs. Functions
![Page 27: COMP 116: Introduction to Scientific Programming Lecture 11: Functions.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/27.jpg)
Why use Functions?
Top-down designEncapsulationMore flexible, resuable codeTesting strategy
![Page 28: COMP 116: Introduction to Scientific Programming Lecture 11: Functions.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/28.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/29.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/30.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/31.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/32.jpg)
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.](https://reader036.fdocuments.us/reader036/viewer/2022062408/56649f125503460f94c25db4/html5/thumbnails/33.jpg)
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.