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? How do we write our own functions? Calling Functions How does MATLAB call its own functions? % MyScript.m x = [4 3 9 2 9 1 2 7 4]; maxX = max(x); ... ... input max.m output 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 Calling Functions How does MATLAB call its own functions? % MyScript.m x = [4 3 9 2 9 1 2 7 4]; maxX = max(x); ... ... input max.m output In MATLAB, each function should go into a separate m-file 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 correctly convert our source code into something the computer understands. Semantics What are semantics? ◦ Meaning ◦ What does your function actually do? ◦ What problem(s) does it solve? 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 Function Syntax Must start with function keyword ◦ Otherwise, it’s a script Function Syntax Function name ◦ Again: remember that this must be the same as the name of the m-file Function Syntax Function return values/output ◦ Potentially multiple values may be returned from the function ◦ [r, c] = size(A) Function Syntax Function input values/parameters ◦ Potentially multiple arguments may be passed into a function ◦ s = sum(A, 2) Function Syntax Comment block, just below the first line ◦ Searched by lookfor ◦ Displayed when you type help Function Syntax Function implementation ◦ Where you do all the ‘work’ ◦ Has comments, expression, function calls… 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 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 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 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 More rules … Function Names are case sensitive ◦ DiceToss is different from dicetoss is different from diceToss… 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; More rules … 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; Gotcha: you can accidently hide system functions, constants, and workspace variables by creating your own function with the exact same name. More rules … Be careful with parentheses:  vs () ◦ [r, c] = size(A) ◦ (r, c) = size(A) ◦ [r, c] = size[A] Incorrect Think: ◦ Difference between myfunc([1, 2, 3]) and myfunc(1, 2, 3) Function examples Multiple inputs No inputs Multiple outputs No outputs 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? Scope Functions run in their own ‘workspaces’ MATLAB foo =4 x2 =5 bar =16 sq.m x =4 x2 =16 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 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 Scripts vs. Functions Why use Functions? Top-down design Encapsulation More flexible, resuable code Testing strategy 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 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 ‘sideeffects’ than scripts 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 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 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 nargin is automatically set in the local workspace of each function, and tells you how many input variables were actually supplied to the function. 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.