Presentation is loading. Please wait.

Presentation is loading. Please wait.

Annoucements Discovery Day (email sent this morning) – Wednesday, April 3 rd : Poster Presentation (Cafeteria) & Slide presentations (COA Atrium). For.

Similar presentations


Presentation on theme: "Annoucements Discovery Day (email sent this morning) – Wednesday, April 3 rd : Poster Presentation (Cafeteria) & Slide presentations (COA Atrium). For."— Presentation transcript:

1 Annoucements Discovery Day (email sent this morning) – Wednesday, April 3 rd : Poster Presentation (Cafeteria) & Slide presentations (COA Atrium). For example: “Formula Hybrid High Voltage System” “Development of Next Generation IPMC Actuator for Flapping Wing UAV” “Mt. Everest Skydiving Research” “Tolerance for Ambiguity of Air Traffic Management Students” COE Forum – Monday, April 8 th at 6PM in the Lehman Atrium – free food! – Each college has representatives on the SGA and they host a forum for their college. Answer questions, give opinions! Arts & Science Aviation Business Engineering NEW: In newest version of MATLAB, tabbing works within the dialog boxes! 1

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

3 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 3

4 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… 4

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

6 General Concept, cont. Huntsville, Alabama. 6 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…

7 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… 7

8 Advantages, there is more! 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. 8

9 and more! 5.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) 6.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?) 7.Modularity: Fixing a function means you don’t have to fix the programs that use the function. 9

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

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

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

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

14 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 14 Function definition Main script file Function call, pass arguments Return info

15 Vocabulary: example1 How many function calls does this program have? 15 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

16 Example, cont. 16 (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

17 Vocabulary: example2 How many function calls does this program show? 17 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

18 Example, cont. 18 (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

19 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

20 General Template, cont. How does the main script file communicate data (back and forth) with each function definition? 20 1. the function name (CALL & DEFINITION), 2. the list of parameters (DEFINITION), 3. the list of return-info (DEFINITION) 4. the actual function body (DEFINITION) 5. the list of arguments (in the CALL), 6. collecting the return-info (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

21 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:  The only disadvantage to using functions: a lot more files in the directory 21 function = ( ) % 1. 2...

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

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

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

25 Remember this? What is the body (i.e. code) of the function? 25 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!

26 Example: changeToLetter.m file 26 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.

27 changeToLetter.m file, 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. % by Caroline 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 27 This is nothing new. This is all new.

28 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

29 6. Calling/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! 29

30 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) 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! 30

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

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

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

34 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? a.fprintf(age, ‘name: %s age: %d\n’, name); b.fprintf(‘name: %s age: %d\n’, name, age); c.fprintf(‘name: %s age: %d\n’, age, name); d.fprintf(age, name, ‘name: %s age: %d\n’);  Which two would not crash on MATLAB? 34 NEW SLIDE

35 THE ORDER MATTERS 35 NEW SLIDE

36 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’); 36

37 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 37 function [var1, var2, var3] = ( ) % [ ] are mandatory

38 8. Application: Shortening Codes! When copy/pasting/changing a little just doesn’t feel right… Assume a code requires 3 inputs, all must be positive numerical values between a specific low/high value. %prompt input1 %validate input1 %prompt input2 %validate input2 %… %ugh… why can’t I write this once and call it 3 times!! 38

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,000 ft^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 39

40 Common questions Does the name of the parameters have to match the name of the arguments? – absolutely not! parameters are “fake” variables arguments are the real ones that contain values 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’. A function is a keyword. 40

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

42 NEVER/RARELY NEVER use input() for your parameters INSIDE the function (unless it’s after trapping the user). parameters gets values from the MAIN script file. 42 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! 43 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! 44


Download ppt "Annoucements Discovery Day (email sent this morning) – Wednesday, April 3 rd : Poster Presentation (Cafeteria) & Slide presentations (COA Atrium). For."

Similar presentations


Ads by Google