1 / 43

Programmer Defined Functions

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). One person can ’ t realistically write and maintain that much code. Programmer Defined Functions.

manon
Download Presentation

Programmer Defined Functions

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. 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. Functions are Everywhere • Any major is broken into smaller tasks and tasks are delegated to project program individuals functions

  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. Task 1 The client gives initial data. Task 2 Project Manager Task 3 Results the client wanted! This may seem similar to EGR101 projects where within a team, students had to split a project into smaller tasks.

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

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

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

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

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

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

  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. 1 0 0 1

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

  32. Step 1 • 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?

  33. Step 2 • 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

  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 documentation!

  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. Parts of the Function Definition • Open the editor, write the function definition line and save the file. • The name of the file MUST be the name of the function.

  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); } clear clc n = 1000000; This is EXACTLY the same code as the single program version

  40. Calling Our Function clear clc for I = 1:8 N = 10^I; MyPi = approx_pi( N ); fprintf(‘%d Iterations: pi = %f\n’, N, MyPi); end 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) 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

More Related