1 / 44

Programmer -Defined Functions

Programmer -Defined Functions. Goals of this Chapter General Concept Advantages Vocabulary (example1, example2) General Template (Examples sind.m , cross.m , changeToLetter.m ) Calling/Testing a function Returning/collecting multiple values Application: steady flight.

marla
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-DefinedFunctions Goals of this Chapter General Concept Advantages Vocabulary (example1, example2) General Template (Examples sind.m, cross.m, changeToLetter.m) Calling/Testing a function Returning/collecting multiple values Application: steady flight

  2. 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. • CAUTION: There is no such thing as a “user-defined” function.. If the user is writing your code, something’s obviously wrong…

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

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

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

  6. Advantages, there are more! • 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 function variables are eliminated after the function executes. • 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. and more! • Readability (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?) • Repair: Fixing a function means you don’t have to fix the programs that use the function.

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

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

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

  11. Vocabulary, cont. Main script file • Calling program/function: The code that will ask the function to execute. • Function definition: the function header and the actual lines of code the function has to execute. • Function call: the command that begins 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: sending information to the function definition. • Return values: information that the function definition calculated and gives back • Return variables: MATLAB’s function variables which must contain the return values when the function completes execution • Collection variables: The calling program’s variables which receive the return values Function definition Function call, passarguments Return values

  12. Vocabulary: example1 • How many functioncalls 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) • 1 • 2 • 3 • 4 • 5

  13. 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) • 1 • 2 • 3 • 4 • 5

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

  15. 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) • 1 • 2 • 3 • More than 3

  16. 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) • 1 • 2 • 3 • More than 3

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

  18. 5. General Template • 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. • Common examples for multiple results are: [nums, txt, raw] = xlsread('Data.xlsx'); [value, location] = max(anArrayOfValues); If MATLAB can do this with built-in functions, we can do this with our own functions too!

  19. General Template, cont. • How does the main script file communicate data (back and forth) with each function definition? the function name (CALL& FUNCTION HEADER), the list of parameters (FUNCTION HEADER), the list of return variables (FUNCTION HEADER) the actual function body (DEFINITION) the list of arguments (in the CALL), collecting the return values (with the CALL) , … 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

  20. Functions: FACTS • “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 and in order: 1. 2. .. function <return info> = <function name>(<parameters>) % <documentation/help> % <author etc..> <function body>

  21. For example: final project • One folder contains the main code, the data files and the function files.

  22. Example: sind() function the name of the file IS the name of the function function is really the first word of the file. title, author and anything else is BELOW.

  23. Example: cross() Only use single % signs for the documentation. %{ %} will not work. Separate by a single blank line to stop the documentation.

  24. Remember this? • What is the body (i.e. code) of the function? 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) Not built-in. Programmer defined!

  25. Example: changeToLetter.mfile 1. 2. .. function <return info> = changeToLetter(<parameters>) % <documentation> <function body> <return info> 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? ___________________ <parameters> 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? ___________________ %documentation is the text that will help other programmers use the function. This shows when F1 is pressed, or when help <function name> is typed in the command window. Using the <parameters> and <return info> variables, code the solution. You can make new variables if you desire.

  26. changeToLetter.mfile, cont. functionequivalentLetter = 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. % by Caroline ifnumericalGrade <0 %error when invalid equivalentLetter = 'ERROR'; elseifnumericalGrade >=90 equivalentLetter = 'A'; elseifnumericalGrade >=80 equivalentLetter = 'B'; elseifnumericalGrade >=70 equivalentLetter = 'C'; elseifnumericalGrade >=60 equivalentLetter = 'D'; else%defaults equivalentLetter = 'F'; end This is all new. This is nothing new.

  27. 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…”)

  28. 6. Calling/Testing a function • Recall one of the advantage to a function: • 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!

  29. Testing a function, cont. • Option 1 – the quickest • Use the Command Window to write a phony function call, just like week1, when you typed: >> x = sind(30) <enter> • Option 2 – the ultimate goal • Create the main script file in charge of calling the execution of a function file. • In either case, be sure to change the directory to the one that contains the function file! – no longer automatic!

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

  31. Option 2 – create a script file %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!)

  32. Common mistake • The “function call” is NOT the “function’s name” Here are 3 examples of “function calls” This file is the “function definition” The name of the function is changeToLetter() regardless!!!!!

  33. NEW SLIDE THE ORDER MATTERS • Whether when collecting values or when passing arguments, respect the order of the variables specified by the function definition. • For example, which one of these works? • fprintf(age, 'name: %s age: %d\n', name); • fprintf('name: %s age: %d\n', name, age); • fprintf('name: %s age: %d\n', age, name); • fprintf(age, name, 'name: %s age: %d\n'); • Which two would not crash on MATLAB?

  34. NEW SLIDE THE ORDER MATTERS • Whether when collecting values or when passing arguments, respect the order of the variables specified by the function definition. • For example, which one of these works? • fprintf(age, ‘name: %s age: %d\n’ , name); • fprintf(‘name: %s age: %d\n’, name, age); • fprintf(‘name: %s age: %d\n’, age, name); • fprintf(age, name, ‘name: %s age: %d\n’); • Which two would not crash on MATLAB? b and c (though results may be weird)

  35. NEW SLIDE THE ORDER MATTERS • Assume the first line of a function definition is as follows: function x = distanceCalculator(velocity,angleDeg,height) Which call in the main code would be appropriate for a projectile with an , , and ? • result = distanceCalculator(154.3,60,45); • result = distanceCalculator(60,45,154.3); • result = distanceCalculator(154.3,45,60); • any of them would return the correct physical result T/F MATLAB will crash on two of these

  36. NEW SLIDE THE ORDER MATTERS • Assume the first line of a function definition is as follows: function x = distanceCalculator(velocity,angleDeg,height) Which call in the main code would be appropriate for a projectile with an , , and ? • result = distanceCalculator(154.3,60,45); • result = distanceCalculator(60,45,154.3); • result = distanceCalculator(154.3,45,60); • any of them would return the correct physical result T/F MATLAB will crash on two of these

  37. 7. Returning multiple values? • COLLECT only UP TO the variable needed! • Example of xlsread() which returns 3 values. function [num, txt, raw] = xlsread(filename) numbers = xlsread(‘data.xlsx’); %numbers only [numbers, txt] = xlsread(‘data.xlsx’); %num and txt [numbers, txt, raw] = xlsread(‘data.xlsx’); %all [~, txt] = xlsread(‘data.xlsx’); %only text (R2009b +) [~, ~, raw] = xlsread(‘data.xlsx’); %only raw data wanted • Example of YOUR functions, which returns 2 values: function [v1, v2] = yourOwnFunction(data1,data2) x = yourOwnFunction(2,’hi’); [x, y] = yourOwnFunction(2,’hi’); [~,y] = yourOwnFunction(2,’hi’);

  38. Returning Multiple values A function may calculate multiple values that need to be returned to the main code. In this case, the template becomes: The function call needs to collect the return values as well: >> [x, y, z] = functionName(argumentList) Of course, this is applicable to an unlimited amount of variables function[var1, var2, var3]= <function name>(<param>) % <documentation/help> <function body> [ ] are mandatory

  39. Problem: steady flight • Due to the size, weight, shape of each aircraft, there is usually one velocity at which the aircraft is steady using the minimum amount of thrust (hence $$$). • “steady” = same altitude, no ups/down • Requirements: • prompt user for weight (60,000lbs to 90,000lbs) • prompt user for surface area (800 ft^2 to 1,000ft^2) • prompt user for drag coefficient (no unit) (“how good the plane resists the air”) between 0 and 1. • solve the minimum thrust • solve the velocity for that thrust

  40. Common questions • Do the parameters have to match the arguments? • Absolutely not! • parameters are variables which exist in the function • arguments are in the calling program / function • it’s still a good habit to name them w.r.t. the content • Can a function call another function? • Absolutely! • note that we’ve done this! just calling an input() command within a function we made is exactly that! MATLAB doesn’t differentiate between built-in and ‘home-made’.

  41. NEVER • NEVER put clear inside a function • you’d be deleting the variables that are needed! Whatever values were passed from the call were just lost… call from the command window (just to test):

  42. NEVER/RARELY • RARELY define your parameters INSIDE the function (unless it’s after trapping the user). Parameters gets values from the MAIN script file. MATLAB already tells you it doesn’t like it.. (orange) Why bother passing values if you’re going to immediately replace their values!!??

  43. 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 and returns the weight of the final payload. (All units are Newtons). • The client also gives the following data: • Create a script file to see if the new keyword works! Weight of Payload = W_structure+ 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

  44. Key ideas Lots of important vocabulary 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. Syntax Only practice will make you remember the syntax. practice, practice, practice! Test these codes tonight!

More Related