programmer defined functions

43
Programmer Defined Functions Matthew Verleger

Upload: manon

Post on 15-Jan-2016

40 views

Category:

Documents


0 download

DESCRIPTION

Programmer Defined Functions. Matthew Verleger. Windows. It ’ s estimated that Window ’ s XP contains 45 million lines of code (and it ’ s over 10 years old). One person can ’ t realistically write and maintain that much code. Programmer Defined Functions. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Programmer Defined Functions

Programmer Defined Functions

Programmer Defined Functions

Matthew VerlegerMatthew Verleger

Page 2: Programmer Defined Functions

Windows

• It’s estimated that Window’s XP contains 45 million lines of code (and it’s over 10 years old).

• One person can’t realistically write and maintain that much code.

Page 3: Programmer Defined Functions

Programmer Defined Functions

• Often called “User Defined Functions,” but in reality they are defined by you, the programmer.

• EVERY programming language still in use (modern or not) includes functions (or may call them subroutines). They are as fundamental as “loops” and “ifs”to programming.

Page 4: Programmer Defined Functions

Goals

• Describe the advantages and disadvantages of writing programmer-defined functions

• Define all the vocabulary (7) involved:

• Function definition

• Function call

• Parameters vs. Arguments

• Return information

• Documentation

• Code body (function body)

• Create a programmer-defined function file and position all the elements correctly

• Test and use a programmer-defined function

Page 5: Programmer Defined Functions

Functions

• sin(), fprintf(), input(), why()

• These are all “programmer-defined functions” that come with MATLAB

• The programmer that defined them works for Mathworks

Page 6: Programmer Defined Functions

• Any major is broken into smaller tasks and tasks are delegated to

Functions are Everywhere

projectprogram

individualsfunctions

Page 7: Programmer Defined Functions

Starbucks

• 1 Person at the register

• 1 Person at the drive-thru

• 1 Person at the espresso machine

Page 8: Programmer Defined Functions

McDonalds

• Manager

• Register/Drinks

• Drive-Thru Taking Orders/Money

• Drive-Thru Giving You Food/Getting Drinks

• Drive-Thru Bags & Counter Trays

• Fryer

• Sandwich Maker

• Cleanup

Page 9: Programmer Defined Functions

Functions

• Functions perform (typically) a single very specific task. They do it well. That’s all they do.

• The Magic Function Boxof Doom!

Page 10: Programmer Defined Functions

VEGAS BABY!

• Functions are like Las Vegas

• What happens in functions stays in functions

• This property is called “Scope”

Page 11: Programmer Defined Functions

Advantages

• Focus

• As the developer, are concerned only about your one function doing it’s task

• You can ignore the rest of the project.

Page 12: Programmer Defined Functions

Advantages

• Portability

• Instead of a single long program, you have a bunch of functions that can all be reused

• People can work on different parts simultaneously

• Parts can be designed to be interchangeable

• Example: The properties of Rocket Engine A are returned by a function. You can use that function on any project where Rocket Engine A is being used.

Page 13: Programmer Defined Functions

Advantages

• Memory Efficiency

• Just like Las Vegas, when you leave, you don’t have to remember what happened there.

• One code will have lots of variables, but the variables used in a function can be cleared when you leave the function.

Page 14: Programmer Defined Functions

Advantages

• Easier to Debug

• Because they are short and specific, they are usually easier to test and verify their correctness

• Can make it easier to test “corner cases” because they can be force-fed into the function.

Page 15: Programmer Defined Functions

Advantages

• Easier to Maintain

• Because code is broken up, if the contents need to change, you only need to update your code in one place

• Example: The model used to estimate structural weight changes - Just update the one structural weight function.

• Example: Pi is now 3. :)

Page 16: Programmer Defined Functions

Disadvantages

• Requires a little more planning and communication

• Functions require inputs and outputs in a specific order

• If you’re splitting a project up, everybody needs to know what that order is

Page 17: Programmer Defined Functions

The client gives initial data.

Results the client

wanted!

Task 1

Task 2

Task 3Project Manage

r

This may seem similar to EGR101 projects where within a team, students

had to split a project into smaller tasks.

Page 18: Programmer Defined Functions

Function definition #1

Function definition #2

Function definition #n

Passing data to the function

Passing data to…

Passing data to…

Getting results back…

Getting results back…

Getting results back…

Main script

file

(Project Manager

)

clcclear

Page 19: Programmer Defined Functions

Main script

file

Function definition #1

Function definition #2

Function definition #n

Passing data to the function

Passing data to…

Passing data to…

Getting results back…

Getting results back…

Getting results back…

(Project Manager

)

"Main Script File"i.e.

THE BOSS.Main script

file

(Project Manager

)

clcclear

Page 20: Programmer Defined Functions

Main script

file

Function definition #1

Function definition #2

Function definition #n

Passing data to the function

Passing data to…

Passing data to…

Getting results back…

Getting results back…

Getting results back…

(Project Manager

)

"Functions Definitions"i.e.

Each smaller piece of code.

Function definition #1

Function definition #2

Function definition #n

clcclear

Page 21: Programmer Defined Functions

Main script

file

Function definition #1

Function definition #2

Function definition #n

Passing data to the function

Passing data to…

Passing data to…

Getting results back…

Getting results back…

Getting results back…

(Project Manager

)

Passing data to the function

Passing data to…

Passing data to…

"Calling the function"i.e.

"Execute this!"

clcclear

Page 22: Programmer Defined Functions

Main script

file

Function definition #1

Function definition #2

Function definition #n

Passing data to the function

Passing data to…

Passing data to…

Getting results back…

Getting results back…

Getting results back…

(Project Manager

)

clcclear

"Passing Arguments"i.e.

Giving Inputs

Passing data to the function

Passing data to…

Passing data to…

clcclear

Page 23: Programmer Defined Functions

Main script

file

Function definition #1

Function definition #2

Function definition #n

Passing data to the function

Passing data to…

Passing data to…

Getting results back…

Getting results back…

Getting results back…

(Project Manager

)

Getting results back…

Getting results back…

Getting results back…

"Return Values"i.e.

Outputs

clcclear

Page 24: Programmer Defined Functions

Vocabulary• Main script file: The script file that contains the

original overall project.

• Function definition: 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. Yes, a function can call a 1st function that can call a 2nd function that calls a 3rd function,…

• Passing arguments: giving inputs to the function definition.

• Return info: final values that the function-definition calculated and gives back

Page 25: Programmer Defined Functions

Example 1

• How many function calls in this code?

• 1

• 2

• 3

• 5

• None of the above

Page 26: Programmer Defined Functions

So if we want to write our own functions:

• Let’s answer the following questions:

• What do we name the function?

• What does the function do?

• What DOESN’T the function do?

• What are the inputs?

• What are the return values of the function?

• What is the output to the screen?

• What are the potential test conditions and the expected output of each test?

Page 27: Programmer Defined Functions

Let’s Write A Function

• Functions are all written in individual files.

• /toolbox/matlab/elfun

• The filename IS the function name

• sin is in sin.m, fprintf is in fprintf.m

• No Spaces

• Only Letters, Numbers, and Underscores

• Can’t start with a number

• Can’t use another keyword/function name

Page 28: Programmer Defined Functions

Input and Output

• 0 or more input arguments

• clc & clear have none

• sin has 1

• fprintf can have a variable number

• 0 or more return values

• clc & clear have none

• sin has 1

• size has a variable number

Page 29: Programmer Defined Functions

Let’s Approximate Pi

• Pi is already a P.D.F. in MATLAB.

• How many input arguments?

• How many return values?

• What if we wanted to implement a method that allowed us to specify how precise we want pi?

Page 30: Programmer Defined Functions

0 10

1

Page 31: Programmer Defined Functions

n

Count = 0Count = 0q = nq = n

Randomly select an x Randomly select an x value between 0 & 1.value between 0 & 1.

Randomly select a y Randomly select a y value between 0 & 1.value between 0 & 1.

Calculate the Calculate the distance from (x,y) to distance from (x,y) to

the originthe origin

Distance Distance <= 1?<= 1?

q > 0?q > 0?

Count = Count Count = Count + 1+ 1

Yes

No

Pi = 4 * (Count / n Pi = 4 * (Count / n ))

Pi

No

Yes

Page 32: Programmer Defined Functions

• What do we name the function?

• What does the function do?

• What DOESN’T the function do?

• What are the inputs?

• What are the return values of the function?

• What is the output to the screen?

• What are the potential test conditions and the expected output of each test?

Step 1

Page 33: Programmer Defined Functions

• Start by writing the code body first

• Let’s us use F5 to test if it is working

• Doesn’t delete all the variables when we are done (which makes debugging easier)

• We’re outside the box

Step 2

Page 34: Programmer Defined Functions

Random Numbers?

• We need to use the random function... let’s find out how

• doc rand

• If you care to know all the various ways to call the function, check out the documentation!

Page 35: Programmer Defined Functions

Rand’s Documentation

• How many inputs can rand take?

• How many outputs does rand give?

Page 36: Programmer Defined Functions

clear

clc

n = 1000000;

q = n;

count = 0;

while( q > 0 )

x = rand(1);

y = rand(1);

if( sqrt(( x^2 + y^2 )) <= 1 )

count = count + 1;

end

q = q - 1;

end

pi = 4 * (count/n)

Page 37: Programmer Defined Functions

Converting it to a Function

• Remove the clear/clc

• Functions should leave things as they are

• clc clears the screen

• clear only deletes the input arguments

• Remove the initialization of n

• We’re going to get this as an input argument

• Add the “function definition” lines

Page 38: Programmer Defined Functions

• Open the editor, write the function definition line and save the file.

• The name of the file MUST be the name of the function.

Parts of the Function Definition

Page 39: Programmer Defined Functions

function MyPi = approx_pi( n )

% pi = approx_pi( n )

% Approx. pi based on the “circle area” algorithm

% n = number of iterations (~10000000 = 3 DP Accuracy)

% Matthew Verleger ([email protected])q = n;

count = 0;

while( q > 0 )

x = rand(1);

y = rand(1);

if( sqrt(( x^2 + y^2 )) <= 1 )

count = count + 1;

end

q = q - 1;

end

MyPi = 4 * (count/n);

}This is EXACTLY the same code as

the single program version

clear

clc

n = 1000000;

Page 40: Programmer Defined Functions

clear

clc

for I = 1:8

N = 10^I;

MyPi = approx_pi( N );

fprintf(‘%d Iterations: pi = %f\n’, N, MyPi);

end

Calling Our Function

q, count, x, and y

don’t exist out

here!

Page 41: Programmer Defined Functions

The Real Advantage of Functions!

function MyPi = approx_pi( n )

% pi = approx_pi( n ) - Approx. pi based on Newton’s algorithm

% n = number of iterations (20 = 6 DP Accuracy)

%Matthew Verleger ([email protected])

MyPi = 0;

for I = 0:n

MyPi = MyPi + ((2^I)*(factorial( I )^2))/factorial( 2*I+1);

end

MyPi = 2*MyPi;

Page 42: Programmer Defined Functions

This also highlights a potential issue

• We have a units issue

• n went from needing to be 10^8 to 20.

• Always think about your input parameters and what changing your function could mean to them

Page 43: Programmer Defined Functions

Summary

• Functions are a great way to break up code into more manageable pieces. Lots of advantages, very few disadvantages

• Functions exist in a box

• The function definition line:

• function [RETURN VALUES]=F_NAME(PARAMETERS)

• %HELP_DOCUMENTATION

• CODE_BODY

• Calling Functions

• Can’t use F5, but will help change directories for you