Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1.

Similar presentations


Presentation on theme: "Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1."— Presentation transcript:

1 Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

2 Definition A function (whether built-in or programmer-defined) is a keyword that executes a specific task. – There IS actual code 'hidden' behind that keyword choice = menu('pick a type of book',… 'fiction','politics','children'); 5 pages! >>edit menu 2

3 Interesting facts… This now explains why programmers shouldn't: – name their own variables as existing keywords! – name their variable as their filename! a = input('a: '); b = input('b: '); input = 56.4; c = input('c: '); 3 input.m clc clear trying =5; trying.m

4 Advantages of functions 1.Shorten codes: 1 keyword instead of 5 pages 2.Re-Usability! (2 keywords instead of 10 pages!) But many more advantages! 4

5 General Concept, cont. Functions are used in every program that matters EGR101 – Rocket Project 5

6 General Concept, cont. Huntsville, Alabama. PARSEC (the Preliminary Analysis of Revolutionary Space Exploration Concepts) at NASA, in Huntsville, Alabama (2005) orbit.m fuel.m fuelsize.m structure.m engine.m geometry.m cost.m THE CLIENT Can you see advantages to working like this? Applied to the Rocket Project… 6

7 Advantages of functions (cont.) 3.Focus! The developers are concerned with the goals of the function, not being distracted by other details of the project. 4.Independence! Instead of one script file that contains the entire software, the software is divided into smaller files. 1.Various engineers can work on their part simultaneously. 2.Engineers can develop code peacefully in their private cube, or even take work home, or on business travel. 3.Engineers can share pieces of codes with other colleagues who are just as specialized as them  feedback, improvements! 4.One engineer can participate in multiple projects: the fuel requirements may be the same for two different rockets… 7

8 Advantages of functions (cont.) 5.Memory efficiency! While a single program may have to keep track of all variables from start to finish, dividing a piece of software into multiple smaller programmer-defined functions lets each function use as many variables as needed, though it only returns the results and deletes any intermediate calculations. choice = menu('pick a type of book',… 'fiction','politics','children'); 1 variable MANY variables 8

9 Advantages of functions (cont.) 6.Easier to debug! Again, instead of one main file where everything has to be completed to work fully, dividing a software into multiple smaller programmer-defined functions: – lets each function be tested separately, regardless of work by other colleagues. Assumptions have to be made, but the function itself can be tested. 7.Clarity: move code from the main program into a separate file, replacing with a single “this is what is being done” command (the function call) 8.Modularity: Fixing a function means you don’t have to fix the programs that use the function. 9

10 2 Disadvantages Since each function is a separate.m file in its own: – LOTS of files to keep track of. 10

11 2 Disadvantages Because a function is designed to operate in a box, MATLAB won’t show you the variables from inside a function in the workspace. This means that debugging usually requires more fprintf statements, pause commands, and fewer semicolons. 8 advantages vs. 2 disadvantages ! 11

12 Key Points MANY Advantages Shortens main code Re-usable Focus Independence Memory-Efficiency Clarity Modularity ONE Disadvantage A lot of.m files A function is a keyword that stands for lots of lines of code. built-in: MATLAB software has the function when you install MATLAB programmer-defined: created by programmers! 12

13 Programmer-defined Functions Vocabulary 1.More precise Global Idea 2.Vocabulary 13

14 General Concept, cont. Huntsville, Alabama. PARSEC (the Preliminary Analysis of Revolutionary Space Exploration Concepts) at NASA, in Huntsville, Alabama (2005) orbit.m fuel.m fuelsize.m structure.m engine.m geometry.m cost.m THE CLIENT Applied to the Rocket Project… 14

15 Overall, it may seem to work like this The client gives requirements: initial inputs. Programmer- defined Function #1 Programmer- defined Function #2 Programmer- defined Function #3 Programmer- defined Function #4 Results the client wanted! 15

16 In reality, there is a boss (project manager) The client 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. 16

17 In reality, there may also be sub-tasks The client initial data. Results the client wanted! Task 1 Task 2 Task 3 Project Manager Task 1.1 Task 1.2 17

18 4. Vocabulary Main script file (Project Manager) clc clear Function definition #1 Function definition #2 Function definition #n Function call, pass arguments Return info How does this relate to programming? 18

19 Vocabulary, cont. Main script file: The script file that contains the original overall project. Function definition: the function header and the actual lines of code the function has to execute. (a little file for each new keyword) 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. (A function CAN call another function you made!) Passing arguments: giving inputs to the function definition. Return info: final variables that the function definition calculated and gives back Collection variables: The variables which receive the return info Function definition Main script file Function call, pass arguments Return info result = 19

20 Vocabulary: example1 How many function calls does this program have? clc clear %ask user for angle angle = input('Enter an angle in degrees: '); %calculate sine of the angle, display results result = sind(angle); fprintf('sine of %.2f degrees is %.2f\n', angle, result) A.1 B.2 C.3 D.4 E.5 20

21 Example, cont. (Project Manager) clc clear input() sind() fprintf() Function call, pass ‘Enter an angle….’ Function call, pass angle Function call, pass ‘string’, angle, result Return value Return-info Function call clc Function call clear no return info Main script file %collect angle = %collect result = IGNORE return info 21

22 Vocabulary: example2 How many function calls does this program show? clc clear %generate random value to evaluate grade grade = rand*100; %find what letter that is, display result letterGrade = changeToLetter(grade); fprintf('With a grade of %.2f, that''s a(n) %c\n', grade, letterGrade) A.1 B.2 C.3 D.More than 3 22

23 Example, cont. (Project Manager) clc clear rand changeToLetter() fprintf() Function call, (pass nothing) Function call, pass grade Function call, pass ‘string’, grade, letterGrade Return value Return result Return-info Function call clc Function call clear no return info Main script file %collect grade = %collect letterGrade = IGNORE return info 23

24 Visual Example: Ordering Pizza 1. you place a call. Pizza Place: crust ingredient1 ingredient2 … 2. pass arguments: 'thin crust' 'pepperoni' 'cheese' 3. execute code (many variables used) 5. collect the result! 4. returns a result 24

25 Key Points Be able to name each step in order, and describe them Be able to define each of the following: – main file – function definition – passing arguments – return values – collecting return-values 25

26 Writing a Re-Usable Function 1.Creating a definition file 2.Arguments vs. parameters 3.Variables in and out of the function 4.Example 26

27 Writing a function definition file Lab16_hazard_RAND.m 27 sticker.m Lab16_hazard_DLMREAD.mLab17_hazard_EXCEL.mLab18_hazard_EXCEL_WHO.m

28 Open a new script file A function always has a name – It follows the same rules as naming any variable What are the inputs? arguments – There may be ZERO to unlimited number of arguments What are the return-values? – There may be ZERO to unlimited number of return-values NAMING VARIABLES: 1.must start with a letter 2.cannot have special characters (except underscore) 3.cannot be an existing keyword 4.keep it less than 63 characters 5.should represent its content HOWEVER. with functions, the name of the function 6.MUST be the name of the file HUGE difference: "What's the function-call?" vs. "What’s the function's name?" "What’s the function called?" Writing a Function 28 CAUTION: we do NOT refer to this as the "Function call"

29 Return-values Variables in and out Function definition Arguments Any form: hardcoded, variables Any shape: scalars, arrays (numerical, cell-arrays, char-arrays…) Any data-type: char, double, string, logical… One form: hardcoded, variables Any shape: scalars, arrays (numerical, cell-arrays, char-arrays…) Any data-type: char, double, string, logical… 29

30 Creating a function file function [return variables] = functionName(parameter list) %FUNCTIONNAME Summary of this function goes here % Detailed explanation goes here % author and version % algorithm and code 1. 2. 3. 4. 5. 6. 7. If there are more than 1 argument or return-value, separate each variable by a comma. functionName.m 30

31 The function definition sticker.m 31 3 parameters were needed

32 Use the parameters in the file 32 …

33 Write the documentation 33 Only use single % signs for the documentation. (Ctrl+R) %{ %} will not make doc work. Separate by a single blank line to stop the documentation. write the name of the function. CAPS. How to call the function?

34 The documentation appears everywhere! 34

35 Basic Rules to make a function definition work The function file AND the main script file should be in the same directory. All the parameters should be used within the function body. – If one is not used, MATLAB will underline in orange and give a warning (“Why do you have this input if you’re not going to use it?”) All the return variables should be assigned a value somewhere within the function body. This is the only way for MATLAB to communicate results with the main script file. – If one is not assigned, MATLAB will underline in orange indicating a warning. (“Somebody using this function might need that value…”) – It will actually crash during run-time! 35 old worksheet

36 Example: Function for a pizza Create a function that helps a company price a pizza. The function needs all 4 values above. The function should print a confirmation message, return the price of the pizza, as well as fee for delivery if necessary. (It should return the two as 2 separate values.) Pizza Place: crust? ingredient1? ingredient2? delivery y/n? 36 Parameters needed

37 Variables in the function vs. in the main script file "What happens in Vegas stays in Vegas". The variables inside the function NEVER make it out of the function. – Possibly identical variables used. DIFFERENT places in memory! – Only values are returned. 37 VEGAS

38 "Arguments" vs. "parameters"? Officially: – parameters: the variables within the function definition that MATLAB uses to process the information given by the arguments – parameters are on a lot of electronic devices – arguments: the actual values used 38

39 Key Points Be able to write a function file Recognize the difference between the variables inside the functions, vs. the ones outside. Write a function-call to test the function Write a new script that uses the function Each function is in a NEW.m file The filename MATCHES the function's name The 1 st word (before your name/section/etc..) IS function Your name/section is LAST on the documentation! The documentation is the text that shows up when other programmers want to use the function YOU wrote The code MUST use the parameter variables The code MUST assign a value to the return-variables 39


Download ppt "Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1."

Similar presentations


Ads by Google