220 likes | 376 Views
Scientific Programming Using MATLAB, Fall 2010-2011. TIRGUL #9: Advanced functions. Lesson outline. Functions with variable numbers of arguments Function handles Nested and sub-functions Evaluations Recursion. Functions with variable numbers of arguments.
E N D
Scientific Programming Using MATLAB, Fall 2010-2011 TIRGUL #9: Advanced functions
Lesson outline • Functions with variable numbers of arguments • Function handles • Nested and sub-functions • Evaluations • Recursion
Functions with variable numbers of arguments • Sometimes functions need to have variable numbers of input / output arguments • Variable #outputs: • H = ttest2(distrib1, distrib2) • [H, pval] = ttest2(distrib1, distrib2) • [H, pval, confidence] = ttest2(distrib1, distrib2) • Variable #inputs: • result = mean(dataMat) • result = mean(dataMat, dim)
How can we write these functions? • varargout – variable number of outputs • varargin – variable number of inputs • These are variables that are only used in functions! • Syntax: • function [out1, out2, varargout] = functionName (in1, in2…, varargin) Mandatory outputs Optional outputs Mandatory inputs Optional inputs
The optional arguments are collected into a cell array and are used according to the way the user called the function • Note: • varargoutand varargin must be declared as the last input/output • Must be all lower-case
Another option • nargout – number of output arguments • nargin – number of input arguments • When used inside functions, they indicate how many outputs/inputs a user has supplied • Note: they count all the arguments, including the obligatory ones • Example: myVarArg.m
You can use any combination of varargout, varargin, nargout, nargin that you need. • Example: varArgEx.m
Function handles • We can create a handle to any MATLAB function, and then pass it as an argument to other functions. • Syntax: • funcHandle = @functionName • Or: • Use str2func
Function handles are a special MATLAB data type • Can be stored in cell arrays / structure arrays • Using function handles – usually for optimization, differential equations, zero finding etc. • Some “function functions”: • fzero, fminsearch, fplot • Example: funcFuncExample.m
Nested and sub-functions • Until now, we’ve known that a function m-file contains one function, and is named according to that function • There are some exceptions to this. We’ll focus on two of them.
MATLAB sub-functions • MATLAB program files can contain code for more than one function. • Additional functions within the file are called sub-functions, and these are only visible to the primary function/script or to other sub-functions in the same file. • Other than visibility, sub-functions are normal functions, that create their own scope, excluding the variables of the “mother” function/script.
Note: checking for sub-functions comes first in the MATLAB search-path. • Examples from mathworks website: http://www.mathworks.com/help/techdoc/matlab_prog/f4-70666.html
Nested functions • These are functions that are defined and called from within a function • The scope includes any variables existing in the “mother” function
When using nested functions • Caution! • nested functions cannot be defined inside a MATLAB flow control statement • if, switch, for, while etc. • If you are using nested functions, you must use end as the last line for each function in the m-file, including the primary one.
Examples from mathworks website: http://www.mathworks.com/help/techdoc/matlab_prog/f4-39683.html
Calling nested functions • From the level immediately above it • A can call B or D, but not C or E • From a function nested at the same level within the same parent function • B can call D, and D can call B • From a function at any lower level • C can call B or D, but not E
The ‘eval’ function • eval = evaluate = execute a string containing a MATLAB expression. • Syntax: • eval(’expression’) • When marking text in the script editor and pressing F9 – what you’re doing is actually using ‘eval’ on those lines.
eval can be used to control the code while the program is running • Following user input • Depending on certain outcomes • etc. • Example: • evalEx.m
Recursion • Simply: when a function calls itself. • Implementing recursion is very easy in MATLAB – just call the function inside its own code, like you call any other function. • Every time the function is called, a new scope is opened, for the current instance of the function. • Example: myRecursion.m
When to use recursion? • Divide a problem into sub-problems of the same type. Examples: • Classic example: factorial • addpath(genpath(‘dir’)) uses recursion to add the directory ‘dir’ and all its sub-directories to search path
Caution • When using recursion, make sure that your program approaches termination – otherwise MATLAB will crash • MATLAB has a default maximum recursion limit of 500 • Use set(0,'RecursionLimit',N) to change the limit Handle for MATLAB “root” object
Practice • Write a function that takes a distribution (data vector) and can calculate the mean, std and range of it. Non of these outputs should be obligatory. If the function is called without any outputs, it should produce a figure with a histogram of the data. • To produce the histogram, create a function handle for the function ‘bar’, and pass it as an argument to the function ‘feval’ • Use recursion to update your ‘interactDiv’ from Ex3 – so that the program runs over and over again until the user wants to quit.