1 / 33

COMP 116: Introduction to Scientific Programming

COMP 116: Introduction to Scientific Programming . Lecture 11: Functions. So far. Script 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 ?

vida
Download Presentation

COMP 116: Introduction to Scientific Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. So far • Script 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?

  3. Calling Functions • How 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.m x = [4 3 9 2 9 1 2 7 4]; maxX = max(x); ... ... input max.m output

  4. Calling Functions • How does MATLAB call its own functions? • In MATLAB, each function should go into a separate m-file % MyScript.m x = [4 3 9 2 9 1 2 7 4]; maxX = max(x); ... ... input max.m output

  5. Syntax vs. Semantics • What 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 correctlyconvert our source code into something the computer understands.

  6. Semantics • What are semantics? • Meaning • What does your function actually do? • What problem(s) does it solve?

  7. 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 shouldbe the same

  8. Function Syntax • Must start with function keyword • Otherwise, it’s a script

  9. Function Syntax • Function name • Again: remember that this must be the same as the name of the m-file

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

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

  12. Function Syntax • Comment block, just below the first line • Searched by lookfor • Displayed when you type help

  13. Function Syntax • Function implementation • Where you do all the ‘work’ • Has comments, expression, function calls…

  14. Jargon • Parameters • The variables declared in the function interface • Arguments • 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

  15. 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 severaloutputs • This is different from most other languages. • Input and output are optional • Comments are optional • But a good programming practice

  16. More rules … • One function per file • Exception: helper functions • Meant to only be used internally by the main function function [avg, med] = newstats(u) % NEWSTATS Find meanw/ subfuctions. n= length(u); avg= helper_mean(u, n); All in a single m file function a = helper_mean(v, n) % Subfunction: calculate average. a = sum(v)/n;

  17. More rules … • Function Names are case sensitive • DiceToss is different from dicetoss is different from diceToss…

  18. More rules … function [avg, med] = newstats(u) % NEWSTATS Find meanw/ subfuctions. n= length(u); avg= helper_mean(u, n); function a = helper_mean(v, n) % Subfunction: calculate average. a = sum(v)/n;

  19. More rules … function [avg, med] = newstats(u) % NEWSTATS Find meanw/ subfuctions. n= length(u); avg= mean(u, n); • Gotcha: you can accidently hide system functions, constants, and workspace variables by creating your own function with the exact same name. function a = mean(v, n) % Subfunction: calculate average. a = sum(v)/n;

  20. 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

  21. Function examples Multiple inputs Multiple outputs No outputs No inputs

  22. Exercise 1 • Write 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?

  23. Scope • Functions run in their own ‘workspaces’ MATLAB sq.m foo =4 bar =16 x2 =5 x =4 x2 =16

  24. 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

  25. 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

  26. Scripts vs. Functions

  27. Why use Functions? • Top-down design • Encapsulation • More flexible, resuable code • Testing strategy

  28. 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

  29. 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

  30. 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

  31. 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

  32. Variable number of inputs • How 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 narginis automatically set in the local workspace of each function, and tells you how many input variables were actually supplied to the function.

  33. Variable number of outputs • How does size()work? • Can return variable number of outputs • varargout, nargout • nargout returns the number of output arguments specified for a function.

More Related