-defined functions 1. goals of this chapter 2. general concept 3. advantages 4. vocabulary 5....

48
-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 (Kind y)

Upload: lorena-mcgee

Post on 19-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

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

-DefinedFunctions

1. Goals of this Chapter

2. General Concept

3. Advantages

4. Vocabulary

5. Examples

6. General Template – Applications1. Definitions, calls (testing) 1

XProgrammerUser

(Kindy)

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

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

2

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

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

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

General Concept, cont.

Used in every program that matters

4

EGR101 – Rocket Project

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

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…

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

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

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

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

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

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

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

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!

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

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.

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

4. Vocabulary

11

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 12: -Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. Vocabulary 5. Examples 6. General Template – Applications 1. Definitions,

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

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

5. Principle applied to built-in functions

Consider the following main script file

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)

Question: How many function calls does this show?A. 1B. 2C. 3D. 4E. 5

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

Example, cont.

14

Main script file

(Project Manager)

clcclear

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

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

Example 2

Consider the following main script file:

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)

Question: How many function calls does this show?A. 1B. 2C. 3D. More than 3

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

Example, cont.

16

Main script file

(Project Manager)

clcclear

rand

changeToLetter()

fprintf()

Function call, pass (nothing!)

Function call, pass grade

Function call, pass ‘string’, grade, letter

Return value

Return a letter

Return-info

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

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

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

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

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

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

<function body>

1.2.

..

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

General Template

20

function <return info> = <function name>(<parameters>)

% <documentation>

<function body>

Why are there <parameters>?

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=3x3-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).

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

Example: sind() function

21

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

Example: cross()

22

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

Remember this? Consider the following main script file:

23

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)

Question: How many function calls does this show?A. 1B. 2C. 3D. More than 3

Not built-in. Programmer defined!

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

Example: build the changeToLetter() function

24

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 25: -Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. Vocabulary 5. Examples 6. General Template – Applications 1. Definitions,

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

end25

This is nothing new.

This is all new.

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

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

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

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

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

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

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

29

Option 1Use the

Command Window to

experiment.

Write function calls.

Test with various arguments.

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

Option 2 – create a script file

30

%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 31: -Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. Vocabulary 5. Examples 6. General Template – Applications 1. Definitions,

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.5Normal weight = 18.5-24.9Overweight = 25-29.9Obesity = BMI of 30 or greater

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

function <return info> = BmiCalculator(<parameter>)% <documentation>

<function body>

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

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

function <return info>=BmiCalculator(height, mass, unitSystem)% <documentation>

<function body>

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

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

3rd 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)% <documentation>

<function body>

Data calculated becomes return info.When more than one variable is to be returned, enclose the return list in a vector, using [ ] .

34

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

4th 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'

<function body> Must use single % only, without skipping one!. 35

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

5th Create the function body

36

Function body is:

%calculate BMIif strcmpi(unitSystem, 'metric')

bmiValue = mass/(height^2);else %had to be 'english'

bmiValue = mass*703/(height^2);end

%Assign correct categoryif 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.5Normal weight = 18.5-24.9Overweight = 25-29.9Obesity = BMI of 30 or greater

36

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

6th Finally, test function

Option 1 – use the Command Window

Option 2 – start a main script file (inside the same directory)

3737

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

Option 1 – Command WindowThis is the ‘experimental’ stage and might teach a lot!

38

Hardcoded arguments, just to test!

Wait.. How come there is only one result?

1 2

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

Option 1, cont.This is ‘experimental’ and might teach a lot!

39

Hardcoded arguments, just to test!

>>>> ASK FOR 2 VARIABLES, GET 2 VARIABLES

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

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

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

Collecting Return Values Suppose a stack of books What if you want the 3rd

book (the yellow one)? You must collect the 1st and

2nd (red and green) before collecting the 3rd (yellow).

41

It is exactly the same with the return info.• They come out in order.• To access the 3rd return value, the code must collect the 1st and

2nd. • To ‘skip’ collecting specific return values… see the next slides…..

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

Use a dummy variable Suppose another client does not care for the BMI value, but

absolutely wants the BMI category?

42Name it dummy, trash, skip, obsolete… anything that says “don’t use it”…

You MUST collect all the return data previous to the one wanted

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

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

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

Option 2 – Main Script File

There are now 2 files in the current directory:

44

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

Option 2, cont.

45

Ask for inputs.

Pass as arguments to a function to solve.

Show results.

Store results.

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

Option 2, cont.

Press F5 on this regular script file, see results in the Command Window.

46

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

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

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

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