330 likes | 475 Vues
This lecture on scientific programming introduces the essential components of MATLAB functions. It discusses the organization of MATLAB code, including the use of script files and the creation of separate function m-files. The lecture covers input and output variables, syntax versus semantics, and the rules for writing functions. Key concepts such as global and local variables, function scope, and the importance of matching function names with m-file names are explored. Additionally, it provides exercises to reinforce understanding of absolute value functions and parameter handling in MATLAB.
E N D
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? • 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
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
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.
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 shouldbe 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 severaloutputs • 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 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;
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 meanw/ 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 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;
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
Function examples Multiple inputs Multiple outputs No outputs No inputs
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 sq.m foo =4 bar =16 x2 =5 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
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 ‘side-effects’ 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 narginis 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.