Presentation is loading. Please wait.

Presentation is loading. Please wait.

User-defined Functions. CS 1112 Scripts Command window: x = 2; my_script Hello! y = x + 2 y = 7 my_script.m: disp( 'Hello!' ); x = 5;

Similar presentations


Presentation on theme: "User-defined Functions. CS 1112 Scripts Command window: x = 2; my_script Hello! y = x + 2 y = 7 my_script.m: disp( 'Hello!' ); x = 5;"— Presentation transcript:

1 User-defined Functions

2 CS 1112 Scripts Command window: x = 2; my_script Hello! y = x + 2 y = 7 my_script.m: disp( 'Hello!' ); x = 5;

3 CS 1113 Scripts A script is just a collection of MATLAB statements Running a script is the same as running the statements in the command window Scripts and the command window share the same set of variables, also called global variables

4 CS 1114 Workspace Workspace is the collection of variables that can be used when a command is executing Scripts and the command window share the same workspace Global variables are problematic because values you depend on may be changed by other scripts

5 CS 1115 Functions A function is a black box that gets some input and produces some output We do not care about the inner workings of a function Functions provide reusable code Functions simplify debugging Functions have private workspaces The only variables in the calling program that can be seen by the function are those in the input list The only variables in the function that can be seen by the calling program are those in the output list

6 CS 1116 Functions function p = factorial(n) %FACTORIAL Factorial function. % FACTORIAL(N) is the product of all the integers from 1 to N, % i.e. prod(1:N). Since double precision numbers only have about % 15 digits, the answer is only accurate for N <= 21. For larger N, % the answer will have the right magnitude, and is accurate for % the first 15 digits. % % See also PROD. % Copyright 1984-2001 The MathWorks, Inc. % $Revision: 1.5 $ if (length(n)~=1) | (fix(n) ~= n) | (n < 0) error('N must be a positive integer'); end p = prod(1:n); output argument input argument Help text statements executable code factorial.m: H1 comment line name of the function

7 CS 1117 Functions the first line of a function file is called function-declaration line and must contain the word function followed by calling syntax for function the name of the function must be the same as the name of the m-file, names are case sensitive Function names must begin with a letter and continue with any combination of letters, numbers and underscores but no spaces or punctuation characters

8 CS 1118 Functions input and output variables identified in the first line are local to the function input variables contain data passed to function and output variables contain data passed from function Function M-file can have zero input arguments and zero output arguments When a function is called, the input variables are not copied into the function’s workspace, but their values are made readable within the function However if any values in the input variables are changed, the array is then copied into the function’s workspace

9 CS 1119 Functions A function file terminates after the last line in the file is executed or whenever a return statement is encountered if a function file contains nested functions each function in the file requires a terminating end statement A function can abort operation and return control to Command window by calling function error

10 CS 11110 Example 1 function [new_first, new_second] =swap (first, second) new_first = second; new_second = first; Function name is swap. Inputs are first and second, outputs are new_first and new_second

11 CS 11111 Example 1 (con't) Call from the command line: >> a = 10; >> b = 20; >> [a, b] = swap(a, b) >> a = 20 >> b = 10

12 CS 11112 Example 2 function plot_cos(min_x, max_x) X = linspace(min_x, max_x, 100); Y = cos(X); plot (X,Y) Function name is plot_cos. No outputs, inputs are min_x and max_x

13 CS 11113 Example 3 function Y = linear(X, m, b) Y = m*X + b; >> x_vals = [1 2 3 4 5]; >> y_vals = linear(x_vals, 2, 0) y_vals = 2 4 6 8 10 Function inputs and/or outputs can be vectors or matrices

14 CS 11114 Example 4 Write a Matlab script file (using functions) that calculates and displays the balance (B) in a bank account that compounds annually. The user should enter the starting balance (A), the interest rate (r) and the number of years (n) B = A(1 + r/100) n

15 CS 11115 Example 4 (con't) Main function file Get user input Calculate final balance Display final balance

16 CS 11116 Example 4 (con't) % this script file calculates the final balance % in a savings account that compounds % annually [initial_balance, interest_rate, num_years] = get_input ; [final_balance] = calc_final_balance (initial_balance, interest_rate, num_years); display_result(final_balance);

17 CS 11117 Example 4 (con't) get_input {no inputs; outputs need to be initial balance, interest rate and number of years} prompt for and read initial balance prompt for and read interest rate prompt for and read number of years

18 CS 11118 Example 4 (con't) function [init_bal, int_rate, num_yrs] = get_input % % get_input prompts for and returns the % three values entered by the user init_bal = input('Enter initial balance: '); int_rate= input('Enter the interest rate: '); num_yrs= input('Enter number of years ');

19 CS 11119 Example 4 (con't) calc_final_balance {inputs are initial balance, interest rate and number of years; output is final balance} final_balance= initial_balance* ((1 + interest_rate/100)^ num_years)

20 CS 11120 Example 4 (con't) function [f_bal] = calc_final_balance (ib, ir, num) % % calc_final_balance accepts 3 input % arguments (the initial balance, the interest % rate, and the number of years) and % returns the final amount in the account f_bal = ib * ((1 + ir/100)^num);

21 CS 11121 Example 4 (con't) display_result {input is final_balance; no outputs} display explanatory string and final balance function display_result (fb) % displays the ending balance with an % explanatory string fprintf ('The ending balance is $%.2f\n', fb)

22 CS 11122 Function Examples function distance = dist2(x1, y1, x2, y2) %DIST2 Calculate the distance between two points % Function DIST2 calculates the distance between % two points (x1,y1) and (x2,y2) in a Cartesian % coordinate system. % Define variables: % x1 -- x-position of point 1 % y1 -- y-position of point 1 % x2 -- x-position of point 2 % y2 -- y-position of point 2 % distance -- Distance between points % Calculate distance. distance = sqrt((x2-x1).^2 + (y2-y1).^2);

23 CS 11123 Function Examples The lookfor command searches functions according to the H1 comment line lookfor distance DIST2 Calculate the distance between two points GFWEIGHT Calculate the minimum distance of a linear... DISTFCM Distance measure in fuzzy c-mean clustering.... The help command displays the comment lines from the H1 line until the first non-comment line help dist2 DIST2 Calculate the distance between two points Function DIST2 calculates the distance between two points (x1,y1) and (x2,y2) in a Cartesian coordinate system.

24 CS 11124 Function Examples % Script file: test_dist2.m % % Purpose: % This program tests function dist2. % % Record of revisions: % Date Programmer Description of change % ==== ========== ===================== % 12/15/98 S. J. Chapman Original code % % Define variables: % ax -- x-position of point a % ay -- y-position of point a % bx -- x-position of point b % by -- y-position of point b % result -- Distance between the points % Get input data. disp('Calculate the distance between two points:'); ax = input('Enter x value of point a: '); ay = input('Enter y value of point a: '); bx = input('Enter x value of point b: '); by = input('Enter y value of point b: '); % Evaluate function result = dist2 (ax, ay, bx, by); % Write out result. fprintf('The distance between points a and b is %f\n',result);

25 CS 11125 Function Examples clear all x1 = 0; y1 = 5; whos Name Size Bytes Class x1 1x1 8 double array y1 1x1 8 double array Grand total is 2 elements using 16 bytes test_dist2 Calculate the distance between two points: Enter x value of point a: 1 Enter y value of point a: 1 Enter x value of point b: 4 Enter y value of point b: 5 The distance between points a and b is 5.000000

26 CS 11126 Function Examples whos Name Size Bytes Class ax 1x1 8 double array ay 1x1 8 double array bx 1x1 8 double array by 1x1 8 double array result 1x1 8 double array x1 1x1 8 double array y1 1x1 8 double array Grand total is 7 elements using 56 bytes x1 x1 = 0 y1 y1 = 5

27 CS 11127 Function Examples Problem: write a function called strsearch that takes a string s and a character c, and returns the number of occurrences of c in s and the index of the first occurrence. Pseudocode: For each character of s in reverse order If character is equal to c increment the counter save the index

28 CS 11128 Function Examples function [ cnt, pos ] = strsearch( s, c ) %STRSEARCH find the number of occurrences of a character in a string % Function STRSEARCH finds the number of occurrences of a character % c in a given string s. It returns both the index of the first % occurrence and the number of occurrences. % It returns 0 for both the index and the number of occurrences if % c does not exists in s. % % By Pinar Senkul, 24/10/2003 pos = 0; cnt = 0; n = length(s); for ii = n:-1:1, if ( s(ii) == c ), cnt = cnt + 1; pos = ii; end two variables declared as output arguments

29 CS 11129 Function Examples [ a, b ] = strsearch( 'abccdecfac', 'c' ) a = 4 b = 3 a = strsearch( 'abccdecfac', 'c' ) a = 4 strsearch( 'abccdecfac', 'c' ) ans = 4

30 CS 11130 Function Examples function [mag, angle] = polar_value(x,y) %POLAR_VALUE Converts (x,y) to (r,theta) % Function POLAR_VALUE converts an input (x,y) % value into (r,theta), with theta in degrees. % Check for (0,0) input arguments, and print out % a warning message. if x == 0 & y == 0 msg = 'Both x any y are zero: angle is meaningless!'; warning(msg); end % Now calculate the magnitude. mag = sqrt(x.^2 + y.^2); % And calculate angle in degrees. angle = atan2(y,x) * 180/pi;

31 CS 11131 Function Examples function [avg, med] = mystats(u) %MYSTATS Find mean and median. % Function MYSTATS calculates the average and median % of a data set. n = length(u); % Calculate average. avg = sum(u)/n; % Calculate median. w = sort(u); if rem(n,2) == 1 med = w((n+1)/2); else med = ( w(n/2) + w(n/2+1) ) / 2; end

32 CS 11132 Functions: Summary Both scripts and functions are saved as m-files Functions are special m-files that receive data through input arguments and return results through output arguments Scripts are just a collection of MATLAB statements Functions are defined by the function statement in the first line Scripts use the global workspace but functions have their own local independent workspaces


Download ppt "User-defined Functions. CS 1112 Scripts Command window: x = 2; my_script Hello! y = x + 2 y = 7 my_script.m: disp( 'Hello!' ); x = 5;"

Similar presentations


Ads by Google