Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Functions Advantages Name, parameters, return info Flow of the data when running functions Menus Functions Applying Functions to Real Projects."— Presentation transcript:

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

2 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 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 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: http://www.mathworks.com/matlabcentral/fileexchange/26581-peakseek Terminology:

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

11 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 (matthew@mverleger.com) 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

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

13 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 (matthew@mverleger.com)matthew@mverleger.com MyPi = 0; for I = 0:n MyPi = MyPi + ((2^I)*(factorial( I )^2))/factorial( 2*I+1); end MyPi = 2*MyPi;

14 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

15 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

16 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 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 = 18.5-24.9 Overweight = 25-29.9 Obesity = BMI of 30 or greater

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

19 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 [ ].

20 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

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

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

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

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

25 3. "Flow" of data 25 2. 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.

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

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

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

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

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

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

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

37 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 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 39 Option 2 cont. Press F5 on the previous script file to see results in the Command Window.

40 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 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 [ ]

42 Error 1: Using F5 Assume this function definition: 42

43 Error 1: Using F5 43

44 Error 2: Nothing seems to change… 44

45 Error 3: Underlined “stuff” 45

46 Error 3: Underlined “stuff” 46

47 Error 3: Underlined “stuff” 47

48 Error 3: Underlined “stuff” 48

49 Error 4: Using clear 49

50 Error 5: Prompting for the parameters again… 50

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

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. 52 [ ]

53 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

54 Wrapping Up 54


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

Similar presentations


Ads by Google