Presentation is loading. Please wait.

Presentation is loading. Please wait.

-Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. Vocabulary 5. Examples 6. General Template – Applications 1. Definitions,

Similar presentations


Presentation on theme: "-Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. Vocabulary 5. Examples 6. General Template – Applications 1. Definitions,"— Presentation transcript:

1 -Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. Vocabulary 5. Examples 6. General Template – Applications 1. Definitions, calls (testing) 1 X Programmer User (Kindy)

2 1. Goals of this Chapter 1. Understand all the advantages of writing programmer- defined functions 2. Know all the vocabulary involved Function definition, Function call, Parameters, Arguments, Return info, Documentation, Code body 3. Easily create a programmer-defined function file, and position all the elements correctly 4. Easily test a programmer-defined function 2

3 2. General Concept sin(), cos(), fprintf(), mod(), input(), were called built-in functions. These functions already exist in MATLAB (they come with the software). This chapter introduces programmer-defined functions. As the vocabulary states, the function is defined (written) by the programmer (you!). It does not pre-exist in MATLAB. 3

4 General Concept, cont. Used in every program that matters 4 EGR101 – Rocket Project

5 General Concept, cont. 5 Huntsville, Alabama. PARSEC (the Preliminary Analysis of Revolutionary Space Exploration Concepts) at NASA, in Huntsville, Alabama. Orbit Specialist Fuel Specialist Size Fuel Tank Structure Specialist Select/Design Engine Vehicle Geometry Estimate Cost THE CLIENT Can you see advantages to working like this? Applied to the Rocket Project…

6 3. Advantages 1. Focus! The developers are concerned with the goals of the function, not being distracted by other details of the project. 2. 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 send pieces of codes to 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… 6

7 Advantages, cont. 3. 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. 4. 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

8 3 Reasons for Functions 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) Re-Use: creating a function allows you to use that function in other programs. (Isn’t it great that somebody did that with the built-in functions?) Modularity: Fixing a function means you don’t have to fix the programs that use the function. 8

9 Overall, it may seem to work like this 9 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!

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

11 4. Vocabulary 11 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?

12 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. 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. 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 12

13 5. Principle applied to built-in functions Consider the following main script file 13 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) Question: How many function calls does this show? A.1 B.2 C.3 D.4 E.5

14 Example, cont. 14 Main script file (Project Manager) clc clear input() sind() fprintf() Function call, pass ‘Enter an angle….’ Function call, pass angle Function call, pass ‘string’, angle, result Return angle Return result Return-info

15 Example 2 Consider the following main script file: 15 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) Question: How many function calls does this show? A.1 B.2 C.3 D.More than 3

16 Example, cont. 16 Main script file (Project Manager) clc clear rand changeToLetter() fprintf() Function call, pass (nothing!) Function call, pass grade Function call, pass ‘string’, grade, letter Return value Return a letter Return-info

17 From both examples: A function always has a name It follows the same rules as naming any variable A function definition receives a set of arguments (inputs). Not fully shown in both examples, but deduced similarly, a function definition can return zero or more results. A common example is: [ value, where ] = max(anArrayOfValues); 17 Value of the maximum Position of the maximum

18 6.1. General Template So, how does everyone communicate data? How does the main script file communicate data (back and forth) with each function definition? 18 1. the return info (with the CALL), 2. the list of arguments (in the CALL), 3. the function name (BOTH), 4. the list of parameters (DEFINITION), 5. the actual function body (DEFINITION) … are all critically placed. Source: http://blogs.msdn.com/willy- peter_schaub/archive/2009/05/16/vsts-rangers-project- tfs2tfs-project-copy-initiative-collaboration-with-the-field- introducing-ait.aspx

19 General Template, cont. “Each MATLAB function definition must be stored in a separate file located in a directory accessible to any script or function that calls it.” Keep it easy: keep main script file and function files in one same folder. The extension is.m just like any other MATLAB file. The name of the file MUST be the name of the function. The file contains specifically: 19 function = ( ) % 1. 2...

20 General Template 20 function = ( ) % Why are there ? Without a list of variables to accept inputs, the function would be a “one-trick pony”. We don’t write programs to solve a specific instance of a problem (e.g. find the roots y=3x 3 -4.2), and we don’t write functions to perform only one instance of a task (e.g. find the sine of 37.2 degrees).

21 Example: sind() function 21

22 Example: cross() 22

23 Remember this? Consider the following main script file: 23 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) Question: How many function calls does this show? A.1 B.2 C.3 D.More than 3 Not built-in. Programmer defined!

24 Example: build the changeToLetter() function 24 function = changeToLetter( ) % 1. 2... is a list of variables that are considered INPUTS to the function definition. What input(s) from the calling program does this function need, if any? ___________________ is a list of variables that are considered OUTPUTS to the function-definition. In other words, the results. What output(s) does this function produce, if any? ___________________ %documentation is the text that will help other programmers use the function. This shows when F1 is pressed, or when help is typed in the command window. Using the and variables, code the solution. You can make new variables if you desire.

25 changeToLetter() function, cont. function equivalentLetter = changeToLetter(numericalGrade) % Use as: % equivalentLetter = changeToLetter(numericalGrade) % % Changes a numerical grade (0-100), to a letter, % following the usual pattern: Above 90 is an A, 80-90 is a B, % 70-80 is a C, 60-70 is a D, below that is an F. if numericalGrade <0 %error when invalid equivalentLetter = 'ERROR'; elseif numericalGrade >=90 equivalentLetter = 'A'; elseif numericalGrade >=80 equivalentLetter = 'B'; elseif numericalGrade >=70 equivalentLetter = 'C'; elseif numericalGrade >=60 equivalentLetter = 'D'; else %defaults equivalentLetter = 'F'; end 25 This is nothing new. This is all new.

26 Basic Rules to make a function definition work 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…”) 26

27 6.2 Testing a function Recall one of the advantage to a function: 4. Easier to debug! … lets each function be tested separately, regardless of work by other colleagues. Assumptions may have to be made, but the function itself can be tested. How can the programmer-defined function changeToLetter() be tested? (Does it really work?) By writing the function _______. This is the command that orders the execution of the function-body. If the function has parameters, F5 is of no use - parameters (inputs) must somehow be given a value! 27

28 Testing a function, cont. Option 1 – the quickest Use the Command Window to write a phony function call Option 2 – the long-goal option Create the main script file in charge of calling the execution of a function file. In either case, make sure to change the directory to the one that contains the function file! – no longer automatic! 28

29 29 Option 1 Use the Command Window to experiment. Write function calls. Test with various arguments.

30 Option 2 – create a script file 30 %clc omitted to see results clear %generate random value to evaluate grade grade = rand*100; %find what letter that is, and display result letterGrade = changeToLetter(grade); %<-- "FUNCTION CALL" fprintf(‘With a grade of %5.2f, that’’s a(n) %c\n', grade,letterGrade) With a grade of 12.70, that's a(n) F With a grade of 91.34, that's a(n) A With a grade of 63.24, that's a(n) D With a grade of 9.75, that's a(n) F With a grade of 27.85, that's a(n) F With a grade of 54.69, that's a(n) F With a grade of 95.75, that's a(n) A With a grade of 96.49, that's a(n) A Ran code 8 times: (Note that since the numerical value is randomize, it is harder to test ALL cases!)

31 1. Try this… Translate the following client requests Create a function which receives 3 arguments (a height, a mass, and the unit system used) and calculates the BMI value (body mass index: a measure of body fat) and the BMI category. The client also gives these as indications: 31 BMI Category depends on BMI value: Underweight <= 18.5 Normal weight = 18.5-24.9 Overweight = 25-29.9 Obesity = BMI of 30 or greater

32 function = BmiCalculator( ) % 1 st Determine a function name Create a function which receives 3 arguments (a height, a mass, and the unit system used) and calculates the BMI value (body-mass-index: a measure of body fat) and the BMI category. 32 Name it so it represents what it does 32

33 function =BmiCalculator(height, mass, unitSystem) % 2 nd Determine a parameter list Create a function which receives 3 arguments (a height, a mass, and the unit system used) and calculates the BMI value (body-mass-index: a measure of body fat) and the BMI category. 33 Inputs received become parameters. Separated by commas, all in ( ). 33

34 3 rd Determine a return info list Create a function which receives 3 arguments (a height, a mass, and the unit system used) and calculates the BMI value (body-mass-index: a measure of body fat) and the BMI category. 34 function [bmiValue, bmiCat] = BmiCalculator(height, mass, … unitSystem) % Data calculated becomes return info. When more than one variable is to be returned, enclose the return list in a vector, using [ ]. 34

35 4 th Document the function Create a function which receives 3 arguments (a height, a mass, and the unit system used) and calculates the BMI value (body-mass-index: a measure of body fat) and the BMI category. 35 function [bmiValue, bmiCat] = BmiCalculator(height, mass, … unitSystem) % Use it as: % [bmiValue, bmiCat] = BmiCalculator(height,mass,unitSystem) % % Calculates Body mass index value and category (etc..) % mass in kg or lbs. height is meters or inches. % unitSystem has to be a string: 'metric', or 'english' Must use single % only, without skipping one!. 35

36 5 th Create the function body 36 Function body is: %calculate BMI if strcmpi(unitSystem, 'metric') bmiValue = mass/(height^2); else %had to be 'english' bmiValue = mass*703/(height^2); end %Assign correct category if bmiValue <=18.5 bmiCat = 'underweight'; elseif … Use variables that exist in the function. ONLY the parameters and return variables exist when the function is first created: height, mass, unitSystem, bmiValue, and bmiCat. BMI Category depends on BMI value: Underweight <=18.5 Normal weight = 18.5-24.9 Overweight = 25-29.9 Obesity = BMI of 30 or greater 36

37 6 th Finally, test function Option 1 – use the Command Window Option 2 – start a main script file (inside the same directory) 37

38 Option 1 – Command Window This is the ‘experimental’ stage and might teach a lot! 38 Hardcoded arguments, just to test! Wait.. How come there is only one result? 12

39 Option 1, cont. This is ‘experimental’ and might teach a lot! 39 Hardcoded arguments, just to test! >>>> ASK FOR 2 VARIABLES, GET 2 VARIABLES

40 Using Return Values When a function returns multiples values, it returns them in a specific order – the order of the return variables. When the function call is written, MATLAB will assign only those return values which have a corresponding collection variable. 40 Confused? It’s only due to vocabulary issues. Once the vocabulary is known, this sentence makes sense…. However, the next slide helps..

41 Collecting Return Values Suppose a stack of books What if you want the 3 rd book (the yellow one)? You must collect the 1 st and 2 nd (red and green) before collecting the 3 rd (yellow). 41 It is exactly the same with the return info. They come out in order. To access the 3 rd return value, the code must collect the 1 st and 2 nd. To ‘skip’ collecting specific return values… see the next slides…..

42 Use a dummy variable Suppose another client does not care for the BMI value, but absolutely wants the BMI category? 42 Name it dummy, trash, skip, obsolete … anything that says “don’t use it”… You MUST collect all the return data previous to the one wanted

43 Use a dummy variable In the latest revisions of MATLAB, the ~ (tilde) has been made available to indicate that you do not want save the return value: 43 [~, Category] = BmiCalculator(userHeight, userMass, units);

44 Option 2 – Main Script File There are now 2 files in the current directory: 44

45 Option 2, cont. 45 Ask for inputs. Pass as arguments to a function to solve. Show results. Store results.

46 Option 2, cont. Press F5 on this regular script file, see results in the Command Window. 46

47 Try it at home… Translate this to a function. Show you tested: Create a function which receives 1 argument (weight of a satellite) and calculates the weight of the final payload. (All units are Newtons). The client also gives the following data: 47 Weight of Payload = W_strusture + W_telemetry + W_power + W_guidance Where: W_structure = 2.16 * W_satellite W_telemetry = 0.78 * W_satellite W_power = 1.24 * W_satellite W_guidance = 1.21 * W_satellite

48 Summary Vocab Function Call, Function Definition, arguments, parameters, return values, return variables, collection variables, dummy variables Concepts Modularity, re-use, clarity; function input, function output, format of a function file; format of a function call; use of parameters to make a function general purpose; collecting or ignoring return values. 48


Download ppt "-Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. Vocabulary 5. Examples 6. General Template – Applications 1. Definitions,"

Similar presentations


Ads by Google