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

Slides:



Advertisements
Similar presentations
A MATLAB function is a special type of M-file that runs in its own independent workspace. It receives input data through an input argument list, and returns.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
The Web Warrior Guide to Web Design Technologies
Introduction to C Programming
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Division Example 2x - 3y + 4z = 10 x + 6y - 3z = 4 -5x + y + 2z = 3 A*X = B where A = B = >> X = A\B X =
Modules, Hierarchy Charts, and Documentation
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Introduction to C Programming
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Introduction to MATLAB ENGR 1187 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
Apply Sub Procedures/Methods and User Defined Functions
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).
1 Chapter One A First Program Using C#. 2 Objectives Learn about programming tasks Learn object-oriented programming concepts Learn about the C# programming.
Add to your agenda! Discovery Day. Wednesday, April 3 rd – all day – Poster Presentation (Cafeteria) & Slide presentations (COA Atrium). For example: “Formula.
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
A First Program Using C#
Functions 1 parameter, 2 return-values "Conversion of time format" One problem. 5 steps to solve it. 1.
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.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Annoucements Discovery Day ( sent this morning) – Wednesday, April 3 rd : Poster Presentation (Cafeteria) & Slide presentations (COA Atrium). For.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
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.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 3 Simple.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Asking the USER for values to use in a software 1 Input.
1 CS161 Introduction to Computer Science Topic #9.
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.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
1. FINISHING FUNCTIONS 2. INTRODUCING PLOTTING 1.
Asking the USER for values to use in a software 1 Input.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
-Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. Vocabulary 5. Examples 6. General Template – Applications 1. Definitions,
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
1 The Software Development Process ► Systems analysis ► Systems design ► Implementation ► Testing ► Documentation ► Evaluation ► Maintenance.
Session 2: PHP Language Basics iNET Academy Open Source Web Development.
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.
Programming Fundamentals Enumerations and Functions.
JavaScript 101 Lesson 6: Introduction to Functions.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
CSC201: Computer Programming
Chapter 3: Using Methods, Classes, and Objects
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
User-Defined Functions
Chapter 3 Simple Functions
Chapter 4 void Functions
Topics Introduction to Functions Defining and Calling a Void Function
Topics Introduction to Functions Defining and Calling a Function
CPS125.
Presentation transcript:

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

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 2

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: '); 3 input.m clc clear trying =5; trying.m

Advantages of functions 1.Shorten codes: 1 keyword instead of 5 pages 2.Re-Usability! (2 keywords instead of 10 pages!) But many more advantages! 4

General Concept, cont. Functions are used in every program that matters EGR101 – Rocket Project 5

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.m cost.m THE CLIENT Can you see advantages to working like this? Applied to the Rocket Project… 6

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

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 8

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

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

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

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

Programmer-defined Functions Vocabulary 1.More precise Global Idea 2.Vocabulary 13

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.m cost.m THE CLIENT Applied to the Rocket Project… 14

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

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

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

4. Vocabulary Main script file (Project Manager) clc clear Function definition #1 Function definition #2 Function definition #n Function call, pass arguments Return info How does this relate to programming? 18

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

Vocabulary: example1 How many function calls does this program have? clc clear %ask user for angle angle = input('Enter an angle in degrees: '); %calculate sine of the angle, display results result = sind(angle); fprintf('sine of %.2f degrees is %.2f\n', angle, result) A.1 B.2 C.3 D.4 E.5 20

Example, cont. (Project Manager) clc clear input() sind() fprintf() Function call, pass ‘Enter an angle….’ Function call, pass angle Function call, pass ‘string’, angle, result Return value Return-info Function call clc Function call clear no return info Main script file %collect angle = %collect result = IGNORE return info 21

Vocabulary: example2 How many function calls does this program show? clc clear %generate random value to evaluate grade grade = rand*100; %find what letter that is, display result letterGrade = changeToLetter(grade); fprintf('With a grade of %.2f, that''s a(n) %c\n', grade, letterGrade) A.1 B.2 C.3 D.More than 3 22

Example, cont. (Project Manager) clc clear 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 Main script file %collect grade = %collect letterGrade = IGNORE return info 23

Visual Example: Ordering Pizza 1. you place a call. Pizza Place: crust ingredient1 ingredient2 … 2. pass arguments: 'thin crust' 'pepperoni' 'cheese' 3. execute code (many variables used) 5. collect the result! 4. returns a result 24

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 25

Writing a Re-Usable Function 1.Creating a definition file 2.Arguments vs. parameters 3.Variables in and out of the function 4.Example 26

Writing a function definition file Lab16_hazard_RAND.m 27 sticker.m Lab16_hazard_DLMREAD.mLab17_hazard_EXCEL.mLab18_hazard_EXCEL_WHO.m

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 letter 2.cannot have special characters (except underscore) 3.cannot be an existing keyword 4.keep it less than 63 characters 5.should represent its content HOWEVER. with functions, the name of the function 6.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"

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

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 If there are more than 1 argument or return-value, separate each variable by a comma. functionName.m 30

The function definition sticker.m 31 3 parameters were needed

Use the parameters in the file 32 …

Write the documentation 33 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?

The documentation appears everywhere! 34

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! 35 old worksheet

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? 36 Parameters needed

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

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

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