programmer -defined functions

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

Upload: marla

Post on 24-Feb-2016

66 views

Category:

Documents


1 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Programmer -Defined Functions

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

1

Page 2: Programmer -Defined Functions

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…

2

Page 3: Programmer -Defined Functions

General Concept, cont.

• Used in every program that matters

3

EGR101 – Rocket Project

Page 4: Programmer -Defined Functions

General Concept, cont.

Huntsville, Alabama.

4

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 5: Programmer -Defined Functions

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…

5

Page 6: Programmer -Defined Functions

Advantages, there are 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 function variables are eliminated after the function executes.

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.

6

Page 7: Programmer -Defined Functions

and more!

5. 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)

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. Repair: Fixing a function means you don’t have to fix the programs that use the function.

7

Page 8: Programmer -Defined Functions

How Programs Work

8

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 9: Programmer -Defined Functions

In reality, there may also be sub-tasks

9

The client initial data.

Results the client wanted!

Task 1

Task 2

Task 3

Project Manager

Task 1.1

Task 1.2

Page 10: Programmer -Defined Functions

4. Vocabulary

10

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 values

Return values

Return values

How does this relate to programming?

Page 11: Programmer -Defined Functions

Vocabulary, cont.• 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 values11

Function definition

Main script file

Function call, pass arguments

Return values

Page 12: Programmer -Defined Functions

Vocabulary: example1

• How many function calls does this program have?

12

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 13: Programmer -Defined Functions

Vocabulary: example1

• How many function calls does this program have?

13

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 14: Programmer -Defined Functions

Example, cont.

14

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

Function call clc

Function call clear

no return values

no return values

Main script file

%collect angle =

%collect result =

IGNOREreturn info

Page 15: Programmer -Defined Functions

Vocabulary: example2

• How many function calls does this program show?

15

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 16: Programmer -Defined Functions

Vocabulary: example2

• How many function calls does this program show?

16

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 17: Programmer -Defined Functions

Example, cont.

17

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

Function call clc

Function call clear

no return info

no return info

Main script file

%collect grade =

%collect letterGrade =

IGNOREreturn info

Page 18: Programmer -Defined Functions

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!

18

Page 19: Programmer -Defined Functions

General Template, cont.

• How does the main script file communicate data (back and forth) with each function definition?

19

1. the function name (CALL & FUNCTION HEADER),2. the list of parameters (FUNCTION HEADER),3. the list of return variables (FUNCTION HEADER)4. the actual function body (DEFINITION)

5. the list of arguments (in the CALL),6. 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

Page 20: Programmer -Defined Functions

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:

20

function <return info> = <function name>(<parameters>)% <documentation/help>

% <author etc..>

<function body>

1.2.

..

Page 21: Programmer -Defined Functions

For example: final project

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

21

Page 22: Programmer -Defined Functions

Example: sind() function

22

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 23: Programmer -Defined Functions

Example: cross()

23

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

Separate by a single blank line to stop the documentation.

Page 24: Programmer -Defined Functions

Remember this?

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

24

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 25: Programmer -Defined Functions

Example: changeToLetter.m file

25

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 26: Programmer -Defined Functions

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

26

This is nothing new.

This is all new.

Page 27: Programmer -Defined Functions

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

27

Page 28: Programmer -Defined Functions

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!

28

Page 29: Programmer -Defined Functions

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!

29

Page 30: Programmer -Defined Functions

Option 1Use the

Command Window to

experiment.

Write function calls.

30

Test with various arguments.

Page 31: Programmer -Defined Functions

Option 2 – create a script file

31

%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 32: Programmer -Defined Functions

Common mistake

• The “function call” is NOT the “function’s name”

32

This file is the “function

definition”

Here are 3 examples of

“function calls”

The name of the function is changeToLetter()

regardless!!!!!

Page 33: Programmer -Defined Functions

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?

33

NEW SLIDE

Page 34: Programmer -Defined Functions

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

b and c (though results may be weird)

Page 35: Programmer -Defined Functions

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: Programmer -Defined Functions

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

36

NEW SLIDE

Page 37: Programmer -Defined Functions

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

Page 38: Programmer -Defined Functions

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 variables38

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

<function body> [ ] are mandatory

Page 39: Programmer -Defined Functions

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: Programmer -Defined Functions

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

40

Page 41: Programmer -Defined Functions

NEVER

• NEVER put clear inside a function– 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: Programmer -Defined Functions

NEVER/RARELY

• RARELY define 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: Programmer -Defined Functions

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: Programmer -Defined Functions

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