Programmer Defined Functions Matthew Verleger
Jan 15, 2016
Programmer Defined Functions
Programmer Defined Functions
Matthew VerlegerMatthew 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
• 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.
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
Functions
• sin(), fprintf(), input(), why()
• These are all “programmer-defined functions” that come with MATLAB
• The programmer that defined them works for Mathworks
• Any major is broken into smaller tasks and tasks are delegated to
Functions are Everywhere
projectprogram
individualsfunctions
Starbucks
• 1 Person at the register
• 1 Person at the drive-thru
• 1 Person at the espresso machine
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
Functions
• Functions perform (typically) a single very specific task. They do it well. That’s all they do.
• The Magic Function Boxof Doom!
VEGAS BABY!
• Functions are like Las Vegas
• What happens in functions stays in functions
• This property is called “Scope”
Advantages
• Focus
• As the developer, are concerned only about your one function doing it’s task
• You can ignore the rest of the project.
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.
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.
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.
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. :)
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
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.
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
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
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
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
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
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
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
Example 1
• How many function calls in this code?
• 1
• 2
• 3
• 5
• None of the above
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?
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
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
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?
0 10
1
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
• 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
• 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
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!
Rand’s Documentation
• How many inputs can rand take?
• How many outputs does rand give?
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)
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
• 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
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;
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!
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;
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
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