Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programmer Defined Functions Matthew Verleger. Windows It’s estimated that Window’s XP contains 45 million lines of code (and it’s over 10 years old).

Similar presentations


Presentation on theme: "Programmer Defined Functions Matthew Verleger. Windows It’s estimated that Window’s XP contains 45 million lines of code (and it’s over 10 years old)."— Presentation transcript:

1 Programmer Defined Functions Matthew Verleger

2 Windows It’s estimated that Window’s XP contains 45 million lines of code (and it’s over 10 years old). One person can’t realistically write and maintain that much code.

3 Programmer Defined Functions Often called “User Defined Functions,” but in reality they are defined by you, the programmer. EVERY programming language still in use (modern or not) includes functions (or may call them subroutines). They are as fundamental as “loops” and “ifs”to programming.

4 Goals Describe the advantages and disadvantages of writing programmer-defined functions Define all the vocabulary (7) involved: Function definition Function call Parameters vs. Arguments Return information Documentation Code body (function body) Create a programmer-defined function file and position all the elements correctly Test and use a programmer-defined function

5 Functions sin(), fprintf(), input(), why() These are all “programmer-defined functions” that come with MATLAB The programmer that defined them works for Mathworks

6 Any major is broken into smaller tasks and tasks are delegated to Functions are Everywhere project program individualsfunctions

7 Starbucks 1 Person at the register 1 Person at the drive-thru 1 Person at the espresso machine

8 McDonalds Manager Register/Drinks Drive-Thru Taking Orders/Money Drive-Thru Giving You Food/Getting Drinks Drive-Thru Bags & Counter Trays Fryer Sandwich Maker Cleanup

9 Functions Functions perform (typically) a single very specific task. They do it well. That’s all they do. The Magic Function Box of Doom!

10 VEGAS BABY! Functions are like Las Vegas What happens in functions stays in functions This property is called “Scope”

11 Advantages Focus As the developer, are concerned only about your one function doing it’s task You can ignore the rest of the project.

12 Advantages Portability Instead of a single long program, you have a bunch of functions that can all be reused People can work on different parts simultaneously Parts can be designed to be interchangeable Example: The properties of Rocket Engine A are returned by a function. You can use that function on any project where Rocket Engine A is being used.

13 Advantages Memory Efficiency Just like Las Vegas, when you leave, you don’t have to remember what happened there. One code will have lots of variables, but the variables used in a function can be cleared when you leave the function.

14 Advantages Easier to Debug Because they are short and specific, they are usually easier to test and verify their correctness Can make it easier to test “corner cases” because they can be force-fed into the function.

15 Advantages Easier to Maintain Because code is broken up, if the contents need to change, you only need to update your code in one place Example: The model used to estimate structural weight changes - Just update the one structural weight function. Example: Pi is now 3. :)

16 Disadvantages Requires a little more planning and communication Functions require inputs and outputs in a specific order If you’re splitting a project up, everybody needs to know what that order is

17 The client gives initial data. Results the client wanted! Task 1 Task 2 Task 3 Project Manager This may seem similar to EGR101 projects where within a team, students had to split a project into smaller tasks.

18 Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… Main script file (Project Manager) clc clear

19 Main script file Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… (Project Manager) "Main Script File" i.e. THE BOSS. Main script file (Project Manager) clc clear

20 Main script file Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… (Project Manager) "Functions Definitions" i.e. Each smaller piece of code. Function definition #1 Function definition #2 Function definition #n clc clear

21 Main script file Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… (Project Manager) Passing data to the function Passing data to… "Calling the function" i.e. "Execute this!" clc clear

22 Main script file Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… (Project Manager) clc clear "Passing Arguments" i.e. Giving Inputs Passing data to the function Passing data to… clc clear

23 Main script file Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… (Project Manager) Getting results back… "Return Values" i.e. Outputs clc clear

24 Vocabulary Main script file: The script file that contains the original overall project. Function definition: the actual lines of code the function has to execute. Function call: the command that calls upon the execution of the code that is inside the function-definition Usually placed within the main script file but can also be within another function-definition. Yes, a function can call a 1st function that can call a 2nd function that calls a 3rd function,… Passing arguments: giving inputs to the function definition. Return info: final values that the function-definition calculated and gives back

25 Example 1 How many function calls in this code? 1 2 3 5 None of the above

26 So if we want to write our own functions: Let’s answer the following questions: What do we name the function? What does the function do? What DOESN’T the function do? What are the inputs? What are the return values of the function? What is the output to the screen? What are the potential test conditions and the expected output of each test?

27 Let’s Write A Function Functions are all written in individual files. /toolbox/matlab/elfun The filename IS the function name sin is in sin.m, fprintf is in fprintf.m No Spaces Only Letters, Numbers, and Underscores Can’t start with a number Can’t use another keyword/function name

28 Input and Output 0 or more input arguments clc & clear have none sin has 1 fprintf can have a variable number 0 or more return values clc & clear have none sin has 1 size has a variable number

29 Let’s Approximate Pi Pi is already a P.D.F. in MATLAB. How many input arguments? How many return values? What if we wanted to implement a method that allowed us to specify how precise we want pi?

30 01 0 1

31 n Count = 0 q = n Randomly select an x value between 0 & 1. Randomly select a y value between 0 & 1. Calculate the distance from (x,y) to the origin Distance <= 1? q > 0? Count = Count + 1 Yes No Pi = 4 * (Count / n ) Pi No Yes

32 What do we name the function? What does the function do? What DOESN’T the function do? What are the inputs? What are the return values of the function? What is the output to the screen? What are the potential test conditions and the expected output of each test? Step 1

33 Start by writing the code body first Let’s us use F5 to test if it is working Doesn’t delete all the variables when we are done (which makes debugging easier) We’re outside the box Step 2

34 Random Numbers? We need to use the random function... let’s find out how doc rand If you care to know all the various ways to call the function, check out the doc umentation!

35 Rand’s Documentation How many inputs can rand take? How many outputs does rand give?

36 clear clc n = 1000000; q = n; count = 0; while( q > 0 ) x = rand(1); y = rand(1); if( sqrt(( x^2 + y^2 )) <= 1 ) count = count + 1; end q = q - 1; end pi = 4 * (count/n)

37 Converting it to a Function Remove the clear/clc Functions should leave things as they are clc clears the screen clear only deletes the input arguments Remove the initialization of n We’re going to get this as an input argument Add the “function definition” lines

38 Open the editor, write the function definition line and save the file. The name of the file MUST be the name of the function. Parts of the Function Definition

39 function MyPi = approx_pi( n ) % pi = approx_pi( n ) % Approx. pi based on the “ circle area ” algorithm % n = number of iterations (~10000000 = 3 DP Accuracy) % Matthew Verleger (matthew@mverleger.com) q = n; count = 0; while( q > 0 ) x = rand(1); y = rand(1); if( sqrt(( x^2 + y^2 )) <= 1 ) count = count + 1; end q = q - 1; end MyPi = 4 * (count/n); } This is EXACTLY the same code as the single program version clear clc n = 1000000;

40 clear clc for I = 1:8 N = 10^I; MyPi = approx_pi( N ); fprintf(‘%d Iterations: pi = %f\n’, N, MyPi); end Calling Our Function q, count, x, and y don’t exist out here!

41 The Real Advantage of Functions! function MyPi = approx_pi( n ) % pi = approx_pi( n ) - Approx. pi based on Newton’s algorithm % n = number of iterations (20 = 6 DP Accuracy) %Matthew Verleger (matthew@mverleger.com)matthew@mverleger.com MyPi = 0; for I = 0:n MyPi = MyPi + ((2^I)*(factorial( I )^2))/factorial( 2*I+1); end MyPi = 2*MyPi;

42 This also highlights a potential issue We have a units issue n went from needing to be 10^8 to 20. Always think about your input parameters and what changing your function could mean to them

43 Summary Functions are a great way to break up code into more manageable pieces. Lots of advantages, very few disadvantages Functions exist in a box The function definition line: function [RETURN VALUES]=F_NAME(PARAMETERS) %HELP_DOCUMENTATION CODE_BODY Calling Functions Can’t use F5, but will help change directories for you


Download ppt "Programmer Defined Functions Matthew Verleger. Windows It’s estimated that Window’s XP contains 45 million lines of code (and it’s over 10 years old)."

Similar presentations


Ads by Google