Top Banner
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
44

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

Dec 29, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Annoucements Discovery Day (email sent this morning) – Wednesday, April 3 rd : Poster Presentation (Cafeteria) & Slide presentations (COA Atrium). For.

1

Annoucements

• Discovery Day (email sent this morning)– Wednesday, April 3rd: 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 8th 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!

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

Programmer-DefinedFunctions

1. Goals of this Chapter2. General Concept3. Advantages4. Vocabulary (example1, example2)5. General Template

(Examples sind.m, cross.m, changeToLetter.m)6. Calling/Testing a function7. Returning/collecting multiple values8. Application: steady flight

2

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

1. Goals of this Chapter

1. Understand all the advantages of writing programmer-defined functions

2. Know all the vocabulary involvedFunction 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

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

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

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

General Concept, cont.

• Used in every program that matters

5

EGR101 – Rocket Project

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

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…

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

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

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

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

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

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

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

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!

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

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.

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

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

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

4. Vocabulary

13

Main script file

(Project Manager)

clcclear

Function definition

#1

Function definition

#2

Function definition

#n

Function call, pass arguments

Function call, pass arguments

Function call, pass arguments

Return info

Return info

Return info

How does this relate to programming?

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

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

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

Vocabulary: example1

• How many function calls does this program have?

15

clcclear %ask user for angleangle = input('Enter an angle in degrees: '); %calculate sine of the angle, display resultsresult = sind(angle);fprintf('sine of %.2f degrees is %.2f\n', angle, result)

A. 1B. 2C. 3D. 4E. 5

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

Example, cont.

16

(Project Manager)

clcclear

input()

sind()

fprintf()

Function call, pass ‘Enter an angle….’

Function call, pass angle

Function call, pass ‘string’, angle, result

Return value

Return value

Return-info

Function call clc

Function call clear

no return info

no return info

Main script file

%collect angle =

%collect result =

IGNOREreturn info

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

Vocabulary: example2

• How many function calls does this program show?

17

clcclear %generate random value to evaluate gradegrade = rand*100; %find what letter that is, display resultletterGrade = changeToLetter(grade);fprintf('With a grade of %.2f, that''s a(n) %c\n', grade, letterGrade)

A. 1B. 2C. 3D. More than 3

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

Example, cont.

18

(Project Manager)

clcclear

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

no return info

Main script file

%collect grade =

%collect letterGrade =

IGNOREreturn info

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

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

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

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

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

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 <return info> = <function name>(<parameters>)% <documentation/help>

% <author etc..>

<function body>

1.2.

..

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

For example: final project

• One folder contains the main code, the data files and the function files.

22

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

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

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

Example: cross()

24

Only use single % signs for the documentation. %{ %} will not work.

Separate by a single blank line to stop the documentation.

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

Remember this?

• What is the body (i.e. code) of the function?

25

clcclear %generate random value to evaluate gradegrade = rand*100; %find what letter that is, display resultletterGrade = changeToLetter(grade);fprintf('With a grade of %.2f, that''s a(n) %c\n', grade, letterGrade)

Not built-in. Programmer defined!

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

Example: changeToLetter.m file

26

function <return info> = changeToLetter(<parameters>)% <documentation>

<function body>

1.2.

.. <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? ___________________

<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? ___________________

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

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

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.

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

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

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

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

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

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

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

Option 1Use the

Command Window to

experiment.

Write function calls.

31

Test with various arguments.

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

Option 2 – create a script file

32

%clc omitted to see resultsclear %generate random value to evaluate gradegrade = rand*100; %find what letter that is, and display resultletterGrade = 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) FWith a grade of 91.34, that's a(n) AWith a grade of 63.24, that's a(n) DWith a grade of 9.75, that's a(n) FWith a grade of 27.85, that's a(n) FWith a grade of 54.69, that's a(n) FWith a grade of 95.75, that's a(n) AWith 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!)

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

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

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

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

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

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 ?a. result = distanceCalculator(154.3,60,45);b. result = distanceCalculator(60,45,154.3);c. result = distanceCalculator(154.3,45,60);d. any of them would return the correct physical

result

T/F MATLAB will crash on two of these

35

NEW SLIDE

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

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

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

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 variables37

function [var1, var2, var3] = <function name>(<param>)% <documentation/help>

<function body> [ ] are mandatory

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

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

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

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

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

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

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

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):

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

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

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

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_satelliteW_power = 1.24 * W_satelliteW_guidance = 1.21 * W_satellite

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

Key ideas

Lots of important vocabulary Function Call, Function Definition, arguments, parameters, return

values, return variables, collection variables, dummy variables

ConceptsModularity, 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.

SyntaxOnly practice will make you remember the syntax. practice, practice, practice! Test these codes tonight!

44