programmer-defined functions advantages vs. disadvantage 1.definition and general idea 2.many...

39
Programmer-Defined Functions Advantages vs. Disadvantage 1. Definition and general Idea 2. Many Advantages 3. 1 Disadvantage 1

Upload: adam-daniel

Post on 21-Jan-2016

234 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

1

Programmer-Defined FunctionsAdvantages vs. Disadvantage

1. Definition and general Idea2. Many Advantages3. 1 Disadvantage

Page 2: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

2

Definition

• A function (whether built-in or programmer-defined) is a keyword that executes a specific task. – There IS actual code 'hidden' behind that keyword

choice = menu('pick a type of book',…'fiction','politics','children');

5 pages!>>edit menu

Page 3: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

3

Interesting facts…

• This now explains why programmers shouldn't:– name their own variables as existing keywords!

– name their variable as their filename!

a = input('a: ');b = input('b: ');input = 56.4;c = input('c: ');

input.m

clccleartrying =5;

trying.m

Page 4: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

4

Advantages of functions

1. Shorten codes: 1 keyword instead of 5 pages2. Re-Usability! (2 keywords instead of 10 pages!)

But many more advantages!

Page 5: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

5

General Concept, cont.

• Functions are used in every program that matters

EGR101 – Rocket Project

Page 6: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

6

General Concept, cont.

Huntsville, Alabama.

PARSEC (the Preliminary Analysis of Revolutionary Space Exploration Concepts) at NASA, in Huntsville, Alabama (2005)

orbit.m

fuel.m

fuelsize.m

structure.m

engine.m

geometry.mcost.m

THE CLIENT

Can you see advantages to working like this?

Applied to the Rocket Project…

Page 7: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

7

Advantages of functions (cont.)

3. Focus! The developers are concerned with the goals of the function, not being distracted by other details of the project.

4. 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 share pieces of codes with 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…

Page 8: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

8

Advantages of functions (cont.)

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

choice = menu('pick a type of book',…'fiction','politics','children');

1 variable MANY variables

Page 9: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

9

Advantages of functions (cont.)

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

8. Modularity: Fixing a function means you don’t have to fix the programs that use the function.

Page 10: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

10

2 Disadvantages

• Since each function is a separate .m file in its own:– LOTS of files to keep track of.

Page 11: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

11

2 Disadvantages

• Because a function is designed to operate in a box, MATLAB won’t show you the variables from inside a function in the workspace. This means that debugging usually requires more fprintf statements, pause commands, and fewer semicolons.

• 8 advantages vs. 2 disadvantages !

Page 12: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

12

Key Points

MANY Advantages

• Shortens main code• Re-usable• Focus • Independence• Memory-Efficiency• Clarity• Modularity

ONE Disadvantage

• A lot of .m files

• A function is a keyword that stands for lots of lines of code. • built-in: MATLAB software has the function when you install MATLAB• programmer-defined: created by programmers!

Page 13: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

13

Programmer-defined FunctionsVocabulary

1. More precise Global Idea2. Vocabulary

Page 14: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

14

General Concept, cont.

Huntsville, Alabama.

PARSEC (the Preliminary Analysis of Revolutionary Space Exploration Concepts) at NASA, in Huntsville, Alabama (2005)

orbit.m

fuel.m

fuelsize.m

structure.m

engine.m

geometry.mcost.m

THE CLIENT

Applied to the Rocket Project…

Page 15: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

15

Overall, it may seem to work like this

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 16: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

16

In reality, there is a boss (project manager)

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 17: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

17

In reality, there may also be sub-tasks

The client initial data.

Results the client wanted!

Task 1

Task 2

Task 3

Project Manager

Task 1.1Task 1.2

Page 18: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

18

4. Vocabulary

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 19: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

19

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

Function definition

Main script file

Function call, pass arguments

Return info

result =

Page 20: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

20

Vocabulary: example1• How many function calls does this program have?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 21: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

21

Example, cont.

(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 22: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

22

Vocabulary: example2

• How many function calls does this program show?

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 23: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

23

Example, cont.

(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 24: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

24

Visual Example: Ordering Pizza

1. you place a call. Pizza Place:crustingredient1ingredient2

2. pass arguments:'thin crust''pepperoni''cheese'

3. execute code(many variables used)

5. collect the result!

4. returns a result

Page 25: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

25

Key Points

• Be able to name each step in order, and describe them• Be able to define each of the following:

– main file– function definition– passing arguments– return values– collecting return-values

Page 26: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

26

Writing a Re-Usable Function

1. Creating a definition file2. Arguments vs. parameters3. Variables in and out of the function4. Example

Page 27: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

27

Writing a function definition file

Lab16_hazard_RAND.m sticker.m

Lab16_hazard_DLMREAD.m

Lab17_hazard_EXCEL.m

Lab18_hazard_EXCEL_WHO.m

Page 28: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

• Open a new script file• A function always has a name

– It follows the same rules as naming any variable

• What are the inputs? arguments– There may be ZERO to unlimited number of arguments

• What are the return-values?– There may be ZERO to unlimited number of return-values

NAMING VARIABLES:1. must start with a letter2. cannot have special characters (except underscore)3. cannot be an existing keyword4. keep it less than 63 characters5. should represent its content

HOWEVER. with functions, the name of the function6. MUST be the name of the file

HUGE difference:

"What's the function-call?"vs.

"What’s the function's name?""What’s the function called?"

Writing a Function

28

CAUTION: we do NOT refer to this as the "Function call"

Page 29: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

29

Return-values

Variables in and out

Function definition

Arguments

Any form:hardcoded, variables

Any shape: scalars, arrays (numerical, cell-arrays, char-arrays…)

Any data-type:char, double, string, logical…

One form:hardcoded, variables

Any shape:scalars, arrays (numerical, cell-arrays, char-arrays…)

Any data-type:char, double, string, logical…

Page 30: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

30

Creating a function file

function [return variables] = functionName(parameter list)%FUNCTIONNAME Summary of this function goes here% Detailed explanation goes here

% author and version

% algorithm and code

1. 2. 3. 4. 5. 6. 7.

If there are more than 1 argument or return-value, separate each variable by a comma.

functionName.m

Page 31: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

31

The function definition sticker.m

3 parameters were needed

Page 32: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

32

Use the parameters in the file

Page 33: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

33

Write the documentation

Only use single % signs for the documentation. (Ctrl+R)%{ %} will not make doc work.

Separate by a single blank line to stop the documentation.

write the name of the function. CAPS.

How to call the function?

Page 34: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

34

The documentation appears everywhere!

Page 35: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

Basic Rules to make a function definition work

• The function file AND the main script file should be in the same directory.

• 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…”)– It will actually crash during run-time!

35old worksheet

Page 36: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

36

Example: Function for a pizza

• Create a function that helps a company price a pizza.

• The function needs all 4 values above. • The function should print a confirmation message, return the price

of the pizza, as well as fee for delivery if necessary. (It should return the two as 2 separate values.)

Pizza Place:crust?ingredient1?ingredient2?delivery y/n?

Parameters needed

Page 37: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

37

Variables in the function vs. in the main script file

"What happens in Vegas stays in Vegas".• The variables inside the function NEVER make it out of the

function. – Possibly identical variables used. DIFFERENT places in memory!– Only values are returned.

VEGAS

Page 38: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

38

"Arguments" vs. "parameters"?

• Officially:– parameters: the variables within the function definition that MATLAB

uses to process the information given by the arguments

– parameters are on a lot of electronic devices

– arguments: the actual values used

Page 39: Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1

39

Key Points

• Be able to write a function file• Recognize the difference between the variables inside the functions, vs. the ones outside.• Write a function-call to test the function• Write a new script that uses the function

• Each function is in a NEW .m file• The filename MATCHES the function's name• The 1st word (before your name/section/etc..) IS function• Your name/section is LAST on the documentation!• The documentation is the text that shows up when other programmers want to use the

function YOU wrote• The code MUST use the parameter variables• The code MUST assign a value to the return-variables