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

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

Chapter 2: Modularization
Copyright © 2002 W. A. Tucker1 Chapter 1 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Chapter 1 - An Introduction to Computers and Problem Solving
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Recursion.
CS 201 Functions Debzani Deb.
Chapter 4 Sec. 4.1, 4.2, 4.4 Procedures (User-defined)
Fibonacci Problem Solving and Thinking in Engineering Programming H. James de St. Germain.
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Functions. Program complexity the more complicated our programs get, the more difficult they are to develop and debug. It is easier to write short algorithms.
Fundamentals of Python: From First Programs Through Data Structures
Add to your agenda! Discovery Day. Wednesday, April 3 rd – all day – Poster Presentation (Cafeteria) & Slide presentations (COA Atrium). For example: “Formula.
Functions 1 parameter, 2 return-values "Conversion of time format" One problem. 5 steps to solve it. 1.
5.1 and 5.4 through 5.6 Various Things. Terminology Identifiers: a name representing a variable, class name, method name, etc. Operand: a named memory.
Functions General Example (+1return values, +1 parameters) 1. The client's wish 2. Creating the function 1. Function's name, Parameter list, Return-info,
1 -Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. How it works Programmer.
1 Functions Advantages Name, parameters, return info Flow of the data when running functions Menus Functions Applying Functions to Real Projects.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
Lecture 8. How to Form Recursive relations 1. Recap Asymptotic analysis helps to highlight the order of growth of functions to compare algorithms Common.
Lecture 4 MATLAB Windows Arithmetic Operators Maintenance Functions
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
1 Computing Software. Programming Style Programs that are not documented internally, while they may do what is requested, can be difficult to understand.
Annoucements Discovery Day ( sent this morning) – Wednesday, April 3 rd : Poster Presentation (Cafeteria) & Slide presentations (COA Atrium). For.
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
‘Tirgul’ # 7 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #7.
Procedures and Functions Computing Module 1. What is modular programming? Most programs written for companies will have thousands of lines of code. Most.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists.
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Algorithms and Algorithm Analysis The “fun” stuff.
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Chapter 1 Program design Objectives To describe the steps in the program development process To introduce the current program design methodology To introduce.
Algorithms & Flowchart
Getting Started with MATLAB (part2) 1. Basic Data manipulation 2. Basic Data Understanding 1. The Binary System 2. The ASCII Table 3. Creating Good Variables.
BMTRY 789 Lecture 11: Debugging Readings – Chapter 10 (3 rd Ed) from “The Little SAS Book” Lab Problems – None Homework Due – None Final Project Presentations.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
The Software Development Process
Lecture 5 1.What is a variable 2.What types of information are stored in a variable 3.Getting user input from the keyboard 1.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
Working With Objects Tonga Institute of Higher Education.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 11 – gdb and Debugging.
EGR 115 Introduction to Computing for Engineers User-Defined Functions1 – Part 1 Wednesday 22 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1.
-Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. Vocabulary 5. Examples 6. General Template – Applications 1. Definitions,
Neal Stublen Breaking Down Tasks  Reduce large tasks into smaller units of code  Smaller units of code might be called any of the.
1 ICS103 Programming in C Lecture 8: Functions I.
CSCI 156: Lab 11 Paging. Our Simple Architecture Logical memory space for a process consists of 16 pages of 4k bytes each. Your program thinks it has.
1 The Software Development Process ► Systems analysis ► Systems design ► Implementation ► Testing ► Documentation ► Evaluation ► Maintenance.
ENG College of Engineering Engineering Education Innovation Center 1 Functions 1 in MATLAB Topics Covered: 1.Uses of Functions Organizational Tool.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
AS Level Computing 8 CHAPTER: Fundamentals of structured programming The basics of good programming Algorithms System Flow Charts Symbol Conventions Steps.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
User-Written Functions
A451 Theory – 7 Programming 7A, B - Algorithms.
Arrays and files BIS1523 – Lecture 15.
User-Defined Functions
Topics Introduction to File Input and Output
Chapter 4 void Functions
Functions In Matlab.
Lab 4: Introduction to Scripting
Software Development Techniques
Presentation transcript:

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 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 project program 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 Box of 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 3 Project Manager 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… Getting results back… Main script file (Project Manager) clc clear

Main script file Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… (Project Manager) "Main Script File" i.e. THE BOSS. Main script file (Project Manager) clc clear

Main script file Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… (Project Manager) "Functions Definitions" i.e. Each smaller piece of code. Function definition #1 Function definition #2 Function definition #n clc clear

Main script file Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… (Project Manager) Passing data to the function Passing data to… "Calling the function" i.e. "Execute this!" clc clear

Main script file Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… (Project Manager) clc clear "Passing Arguments" i.e. Giving Inputs Passing data to the function Passing data to… clc clear

Main script file Function definition #1 Function definition #2 Function definition #n Passing data to the function Passing data to… Getting results back… (Project Manager) Getting results back… "Return Values" i.e. Outputs clc clear

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

01 0 1

n Count = 0 q = n Randomly select an x value between 0 & 1. Randomly select a y value between 0 & 1. Calculate the distance from (x,y) to the origin Distance <= 1? q > 0? Count = Count + 1 Yes No 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 doc umentation!

Rand’s Documentation How many inputs can rand take? How many outputs does rand give?

clear clc n = ; 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 (~ = 3 DP Accuracy) % Matthew Verleger 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 = ;

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