Chapter 6 User-Defined Functions dr.dcd.h CS 101 /SJC 5th Edition 1
MATLAB Functions M-files are collections of MATLAB statements that stored in a file, called a script file. Script files share the command window s workspace, so any variables created by the script files remain in the workspace after the script file finishes executing. A script file has no input arguments returns no results, but they communicate through the data left behind in the workspace. dr.dcd.h CS 101 Spring 2009 2
MATLAB Functions 2 A MATLAB function is a special type of M- file that runs in its own independent workspace. A MATLAB function receives input data through an input argument list and returns results to the caller through an output argument list. A MATLAB function should be placed in a file with the same name as the function with an extension of.m. dr.dcd.h CS 101 Spring 2009 3
MATLAB Functions 3 A function consists of three components For example: a = cos(x) output argument function name input argument All functions, whether they are build-in or user-defined functions, are available for any M-file programs dr.dcd.h CS 101 Spring 2009 4
Syntax The general form of a function as function [outarg1, outarg2, ] = funcname(inarg1, inarg2, ) % H1 % other comments Function statements (return/end) The function keyword marks the beginning of the function. If there are only one output argument, the brackets can be dropped. Input arguments are placeholders for values. dr.dcd.h CS 101 Spring 2009 5
Syntax 2 The comments block following the function statement is called the help block. The first line of it is called the H1. It should contain a one-line summary of the purpose of the function. H1 will be searched and displaced by lookfor, while the whole help block will be displaced if the command help keyword is used. Execution begins at the top and ends when either a return, an end, or the end of the function is reached. dr.dcd.h CS 101 Spring 2009 6
Syntax 3 For debugging purpose, it may be useful to print intermediate results to the command window. However, once you complete your debugging make sure that all your output is suppressed. If you don t, you ll see extraneous information in the command window. It means that you should use ; at the end of every statement. dr.dcd.h CS 101 Spring 2009 7
Pass-by-Value When a function is called, MATLAB makes a copy of the actual arguments and passes them to the workspace of the function. If the passed arguments are modified, it won t affect the original data in the caller. Command window s workspace x = 5; a = abc(x) cw.x abc.x Function abc s workspace function out=abc(in) abc.in abc.x dr.dcd.h CS 101 Spring 2009 8
Local Variables Variables defined in an M-file function, only have meaning inside that program. The only way to communicate between functions and the workspace, is through the function input and output arguments. dr.dcd.h CS 101 Spring 2009 9
Example 1: dist2(x 1,y 1,x 2,y 2 ) The distance between two points (x 1, y 1 ) and (x 2, y 2 ) can be defined as dr.dcd.h CS 101 Spring 2009 10
H1 & Help Block After applying help and lookfor, function dist2 provides the following results. dr.dcd.h CS 101 Spring 2009 11
Example 2: [x,y]=polar2rect(r,q) Convert polar coordinates (r,q) to rectangular form (x,y). dr.dcd.h CS 101 Spring 2009 12
Example 3: [r,q]=rect2polar(x,y) Convert rectangular coordinates (x,y) to polar form (r,q). dr.dcd.h CS 101 Spring 2009 13
Example 4: Selection Sort State the problem. Sort the data into ascending or descending order using the selection sort algorithm. Define the input/output. The inputs are typed by the user, and the outputs are the sorted data written to the command window. Describe the algorithm. - Input an array of n values; - Set the index i equals to1; - Scan and locate the i-th minimum value; - Swap the i-th minimum with the i-th element; - repeat n-1 times. dr.dcd.h CS 101 Spring 2009 14
Example 4: Selection Sort 2 dr.dcd.h CS 101 Spring 2009 15
Optional Arguments Some function may support arbitrary numbers of arguments. For example: plot(x, y); plot(x, y, :ok ); Plot(x, y, :ok, MarkerSize, 3); Functions that can be used to furnish optional arguments nargin, nargout, nargchk varargin, varargout error, warning inputname dr.dcd.h CS 101 Spring 2009 16
Optional Arguments 2 nargin: the number of actual input arguments. nargout: the number of actual output arguments. nargchk: this function returns an error message if too few or too many arguments are used. - syntax: nargchk(min, max, nargin) varargin: the list of variables for actual input arguments. varargout: the list of variables for actual output arguments. dr.dcd.h CS 101 Spring 2009 17
Optional Arguments 3 error: display an error message and abort if a fatal error was caught when a function is called. If its input argument is an empty string, then it does nothing. warning: display a warning message and resume the execution of a function. inputname: this function returns the actual name of the dummy argument. dr.dcd.h CS 101 Spring 2009 18
Optional Arguments 4 dr.dcd.h CS 101 Spring 2009 19
Homework Assignment #12 Quiz 6.1 Page 251: 6, 7 This assignment is due by the next week. Late submission will be penalized. dr.dcd.h CS 101 Spring 2009 20
Global Memory MATLAB functions can also exchange data with each other with the base workspace through global memory. Global memory is a specifal type of memory that can be accessed from any workspace. A global variable is declared as global variable The default value for a global variable is empty, so an initialization is required. dr.dcd.h CS 101 Spring 2009 21
Global Memory 2 An example: To count how many time a function is called. An alternative example: Two functions are used to modify a global counter. dr.dcd.h CS 101 Spring 2009 22
Global Memory 3 dr.dcd.h CS 101 Spring 2009 23
Random Number Generator It is important to know that the real world does not provide perfect measurements. So the ideal simulated data needs to add some random noise. The simulated noise is usually created by a random number generator. The build-in random number generator function rand generates values in the range of [0.0, 1.0). Then the generated noise values can be scaled and leveled. dr.dcd.h CS 101 Spring 2009 24
Random Number Generator 2 The random numbers are in fact generated by a deterministic function; i.e. the sequence of numbers are fixed. The function returns a different and apparently random number each time it is called. It is because the function has started at a different starting point internally each time it is called. The starting point is called a seed and it is set as a global valable. dr.dcd.h CS 101 Spring 2009 25
Random Number Generator 3 Example: two set of random numbers in the range of [-0.5, 0.5]. dr.dcd.h CS 101 Spring 2009 26
Example 6.4: User Defined Random Number Generator A simple random number generator can be defined by the following equation: n 1 = a random seed n i+1 = mod(8121*n i +28411, 134456) ran i = n i 134456 where 134456 is the total highest number in the sequence and each new n i+1 is set as the next seed. dr.dcd.h CS 101 Spring 2009 27
Example 6.4: User Defined Random Number Generator 2 dr.dcd.h CS 101 Spring 2009 28
Example 6.4: User Defined Random Number Generator 3 dr.dcd.h CS 101 Spring 2009 29
Persistent Memory When a function finishes executing, the workspace created for that function is destroyed, so all local variables within that workspace will disappear. The next time the same function is called, a new workspace will be created. Sometimes, it is necessary to preserve local variables between calls to a function. dr.dcd.h CS 101 Spring 2009 30
Persistent Memory 2 Persistent memory is a special mechanism to allow local variables to be preserved between calls to a function. Syntax: persistent variable dr.dcd.h CS 101 Spring 2009 31
Persistent Memory 3 To rewrite a previous example: To count how many time a function is called. dr.dcd.h CS 101 Spring 2009 32
Persistent Memory 4 How to reset the associated counter? dr.dcd.h CS 101 Spring 2009 33
Homework Assignment #13 6.9 Exercises Page 268: 6.6, 6.7, 6.14 This homework is for your reference. dr.dcd.h CS 101 Spring 2009 34