1 Functions Advantages Name, parameters, return info Flow of the data when running functions Menus Functions Applying Functions to Real Projects.

Slides:



Advertisements
Similar presentations
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Advertisements

Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Chapter 6: User-Defined Functions I
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
CS 201 Functions Debzani Deb.
Chapter 6: User-Defined Functions I
Guide To UNIX Using Linux Third Edition
Chapter 3 Planning Your Solution
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
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).
Advanced Shell Programming. 2 Objectives Use techniques to ensure a script is employing the correct shell Set the default shell Configure Bash login and.
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,
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
1 -Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. How it works Programmer.
Lecture 4 MATLAB Windows Arithmetic Operators Maintenance Functions
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Mail merge I: Use mail merge for mass mailings Perform a complete mail merge Now you’ll walk through the process of performing a mail merge by using the.
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.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
1. Reminder of Symbols 2. Dialog Boxes 3. listdlg() 4. msgbox() 5. questdlg() 6. menu() Dialog Boxes Applications of Cell-Arrays 1.
Introduction to File I/O High-Level Functions 1.Data files 2."High level" File I/O 3.dlmread() 4.xlsread() 1.
1. Definition and General Structure 2. Small Example 1 3. Simplified Structure 4. Short Additional Examples 5. Full Example 2 6. Common Error The for loop.
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.
School of Computer Science & Information Technology G6DICP - Lecture 9 Software Development Techniques.
Linux Operations and Administration
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
CMPS 1371 Introduction to Computing for Engineers MatLab.
File I/O High-Level Functions 1. Definition 2. Is a High-Level function appropriate? 3. xlsread() 4. dlmread() 1.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
CPS120: Introduction to Computer Science Lecture 14 Functions.
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 &
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.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
Asking the USER for values to use in a software 1 Input.
Covenant College November 27, Laura Broussard, Ph.D. Professor COS 131: Computing for Engineers Chapter 5: Functions.
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.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
1. FINISHING FUNCTIONS 2. INTRODUCING PLOTTING 1.
Programmer-Defined Functions Advantages vs. Disadvantage 1.Definition and general Idea 2.Many Advantages 3.1 Disadvantage 1.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Asking the USER for values to use in a software 1 Input.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Lecture 6: Output 1.Presenting results in a professional manner 2.semicolon, disp(), fprintf() 3.Placeholders 4.Special characters 5.Format-modifiers 1.
-Defined Functions 1. Goals of this Chapter 2. General Concept 3. Advantages 4. Vocabulary 5. Examples 6. General Template – Applications 1. Definitions,
Cell Arrays Lecture 2/8/ Data Types (Review) 2. General Concept 3. Using Cell-Arrays 1. Syntax/Symbols 2. Dialog Boxes 1.
Early File I/O To help you get started with your final project 1. Definition of “high level” 2. Is using a High Level function appropriate? 3. xlsread()
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined 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.
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Digital Electronics and Computer Interfacing Tim Mewes 2. LabVIEW Basics part II.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Chapter 6: User-Defined Functions I
Dialog Boxes Applications of Cell-Arrays
Scripts & Functions Scripts and functions are contained in .m-files
Functions.
User-Defined Functions
Introduction to Functions
Chapter 6: User-Defined Functions I
CSCI N317 Computation for Scientific Applications Unit 1 – 1 MATLAB
Using Script Files and Managing Data
Presentation transcript:

1 Functions Advantages Name, parameters, return info Flow of the data when running functions Menus Functions Applying Functions to Real Projects

2 Functions Why functions? Clarity – Replace multiple lines of code with a single function call Modularity – Edit / replacement easily performed without impacting calling program Reuse – Function can be shared for use with other programs

3 Function Review 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing

4 Functions Function definition: The code that performs the task for which the function was created. function [locs pks]=peakseek(x, minpeakdist, minpeakh) % documentation *Source: Terminology:

5 Functions Function header – top line of function definition function [locs, pks]=peakseek(x, minpeakdist, minpeakh) Function name ParametersReturn variables What you want to call the function; also the main part of the file name Variables in the function that receive a copy of the input values Variables in the function that will receive the output values All of the variables – parameters and return variables - are “local” to the function. This means that they only exist (and are only usable) in the function. Every function has its own variables!

6 Functions Function call – the command telling MATLAB to execute the function definition [indx, xvals] = peakseek(xvector, min_dist, min_h) Function name – “go execute this function” Arguments (input values) Argument variables exist in the calling program – they are NOT variables from the function! Collection variables – these variables receive the values returned by the function (the values stored in the return variables) – information to be used by the function. These values are copied into the corresponding parameters of the function

7 Functions Function call Function header function [locs pks]=peakseek(x, minpeakdist, minpeakh) [indx xvals] = peakseek(xvector, min_dist, min_h) Arguments copied into parameters Return values copied into collection variables The function body executes: it uses these values to calculate the values of return-values.

8 Functions Main program (test.m): Function (peakseek.m):. [indx, xvals] = peakseek(xvector, min_dist, min_h). function [locs, pks]=peakseek(x,minpeakdist, minpeakh). “Going” “Returning” Variables inside functions are NOT available in the main program (or other functions). Likewise for variables in the main program – they are not available in the functions! 8

9 Real life: Menus Example function – process menu: function destination = ShowMenu(dests) % Use it as: destination = ShowMenu(dests) % decides which destination user wants %find how many option user has s = size(dests); rows = s(1); %store # of rows choice = 0; %so loop runs once while choice rows || mod(choice,1)~=0 clc fprintf('Where do you want to go? \n'); %show each destination for d = 1:rows fprintf('%d. %s\n', d, dests(d, :)); end choice = input(‘Enter destination number:'); end %copy actual final destination destination = dests(choice, :); Example function call % Make the option list dests = strvcat('Atlanta', 'Chicago', 'New York'); % Call the function option = ShowMenu(dests); Where do you want to go? 1. Atlanta 2. Chicago 3. New York Enter destination number:2

10 Functions As programs grow, begin thinking of programs as sequences of “code blocks”. Code blocks are sections of the program that together perform a task or are naturally aligned. Frequently, these code blocks fit naturally into functions. Just a few examples: - showing and processing a menu - reading / writing disk files - numeric computations

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

Testing Experiment in the command window with function calls Replace the parameter by a real value The function returns a value. It is stored in the default variable name ans as usual. 14

Wrapping Up To create a function: 1. Open the editor, type function, the return-info, the name, the parameters, the documentation, then the code 2. Save the file. Match the filename with the name of the function. 3. Change the directory so the function shows in the Current Directory panel 4. Test thoroughly in the command window 5. Once complete, build the main code 6. Test thoroughly again! Now you can combine arrays, functions, loops together from now on! 15

Functions Multiple arguments & return values 1. The client's wish 2. Creating the function 1. Function's name, Parameter list, Return-info, Documentation, and Code Body, saving it. 3. Testing in the command window 4. Testing with a main file 5. A new client comes along 1. Ignoring return values 16

17 1. The client's wish: Create a function which receives 3 arguments (a height, a mass and the unit system used) and calculates the BMI value (body-mass-index: a measure of body fat) and the BMI category. The client also gives these as indications: BMI Category depends on BMI value: Underweight <=18.5 Normal weight = Overweight = Obesity = BMI of 30 or greater

Step2. I/O of the function 3 parameters, 2 return-values 18 bmiCalculator() Unit system Bmi value weight height Bmi category

2. Determine the return-info Create a function which receives 3 arguments (a height, a mass, and the unit system used) and calculates the BMI value (body-mass-index: a measure of body fat) and the BMI category. 19 Data calculated becomes return info. When more than one variable comes back enclose the return list inside [ ].

2. Choose a function name Create a function which receives 3 arguments (a height, a mass, and the unit system used) and calculates the BMI value (body-mass-index: a measure of body fat) and the BMI category. 20 Name it so it represents what it does

2. Create the parameter list Create a function which receives 3 arguments (a height, a mass, and the unit system used) and calculates the BMI value (body-mass-index: a measure of body fat) and the BMI category. 21 Inputs received become parameters. Separated by COMMAS all in ( ).

2. Save the function Save the function in the directory of your choice, 22 But keep the filename that MATLAB gives you by default.

2. Create the function body 23 BMI Category depends on BMI value: Underweight <=18.5 Normal weight = Overweight = Obesity = BMI of 30 or greater

3. "Flow" of data Values for these parameters will come from the arguments in the function call.

3. "Flow" of data Using only the given parameters, this code executes, thus solving for the return values. One day, if needed, you may define new variables to compute intermediate steps. Remember that all these variables are deleted when the function is done with its job.

3. "Flow" of data MATLAB returns the values.

3. Testing - Experiment This is the ‘experimental’ stage! 27 Hardcoded arguments just to test! The function returns two VALUES. >>>>>> Remember to create two VARIABLES capable of holding those two values.

28 >>[x,y]=bmiCalculator(1.65,55,'metric') 1. PASS 2. USE and CALCULATE 3. STORE RESULTS IN RETURN VARIABLES 4. RETURN 5. COLLECT Flow of data

29 4. Testing - Main file There will now be 2 files in the current directory: The algorithm is: % prompt unit system % prompt height and weight % calculate bmi and status % display both

30 4. Code 1 – CLI (Command Line Interface) 1. Ask for inputs. 2. Pass arguments to the function. 4. Show results. 3. Collect the return values.

4. Hit F5 to run This is a regular script file, so hitting F5 is valid. 31

4. Code 2 – dialog boxes questdlg() inputdlg() msgbox() 32

33 Don't hesitate to try this code. It's fun! This is the function call

Almost Wrapping Up Meet with the client, give the software, go on vacations… But another client just walks in, having heard of the bmiCalculator… His request is slightly different: "I just care about the category, not the actual value of the bmi. Can you help me?" 34

35 5. Ignoring Return Values Suppose a stack of books What if you want the 3 rd book (the yellow one) from the top? You must collect the 1 st and 2 nd (red and green) before collecting the 3 rd (yellow). It is exactly the same with the return-values. They come out in order. To access the 3 rd return value the code must collect the 1 st and 2 nd.

5. Ignoring Return Values Every variable UP TO the one wanted must be collected in a variable. (but the later ones may be skipped) Trick: name the variable trash, dummy, ignore, a word that obviously reflects that it is not-to-be used later. You may even delete that variable specifically using clear 36 Try it! Look at the Workspace.

5. Ignoring Return Values Use the 'tilde' operator 37 The ~ indicates "there is no need to store it". COMMA IS MANDATORY. SAME function, DIFFERENT call. Yay! MATLAB version 7.9 (R2009b) and up ONLY

38 Previous version of MATLAB Previous versions of MATLAB do not allow the use of the ~ symbol. Use a dummy variable name to store the data. The name reminds YOU (programmer) that this variable is of no use later on, so choose wisely! It is a MUST to collect all the return data to the left of the one wanted.

39 Option 2 cont. Press F5 on the previous script file to see results in the Command Window.

Wrapping Up Try it out! Type-up this example and make it work. At most, this should take 15 minutes. In order: 1. Create a function file. 2. Save it and change to the directory where it is. 3. Test and experiment in the command window 4. Create the main file afterwards Only practice makes perfect, and the more functions you create, the easier programming will get: INCLUDING the final project! 40

41 Common Errors Programmer Defined Functions 1. Using F5 2. “Nothing seems to be different between each run” 3. Lots of words underlined orange 4. Using clear 5. Prompt again within the function 6. Forgetting the commas, and the [ ]

Error 1: Using F5 Assume this function definition: 42

Error 1: Using F5 43

Error 2: Nothing seems to change… 44

Error 3: Underlined “stuff” 45

Error 3: Underlined “stuff” 46

Error 3: Underlined “stuff” 47

Error 3: Underlined “stuff” 48

Error 4: Using clear 49

Error 5: Prompting for the parameters again… 50

Error 6: Syntax Errors Know your general syntax rules 1. Multiple parameters must be separated by commas. 51

Error 6: Syntax Errors Know your general syntax rules 1. Multiple parameters must be separated by commas. 2. Multiple return-values must be enclosed in square brackets. 3. Omit the equal sign if there is no return value. 52 [ ]

Error 6: Syntax Errors Know your general syntax rules 1. Multiple parameters must be separated by commas. 2. Multiple return-values must be enclosed in square brackets. 3. Omit the equal sign if there is no return value. 53

Wrapping Up 54