scientific programming using matlab fall 2011 2012 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Scientific Programming Using MATLAB, Fall 2011-2012 PowerPoint Presentation
Download Presentation
Scientific Programming Using MATLAB, Fall 2011-2012

Loading in 2 Seconds...

play fullscreen
1 / 23

Scientific Programming Using MATLAB, Fall 2011-2012 - PowerPoint PPT Presentation

Download Presentation
Scientific Programming Using MATLAB, Fall 2011-2012
An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Scientific Programming Using MATLAB, Fall 2011-2012 TIRGUL #8: Advanced functions

  2. Lesson outline • Functions with variable numbers of arguments • Function handles • Nested and sub-functions • Evaluations • Recursion

  3. 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)

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

  5. The optional arguments are collected into a cell array and are used according to the way the user called the function • Note: • varargout and varargin must be declared as the last input/output • Must be all lower-case

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

  7. You can use any combination of varargout, varargin, nargout, nargin that you need. • Example: varArgEx.m

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

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

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

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

  12. Note: checking for sub-functions comes first in the MATLAB search-path. • Examples from mathworks website:

  13. Nested functions • These are functions that are defined and called from within a function • The scope includes any variables existing in the “mother” function

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

  15. Examples from mathworks website:

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

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

  18. eval can be used to control the code while the program is running • Following user input • Depending on certain outcomes • etc. • Example: • evalEx.m

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

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

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

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

  23. More practice (from last year’s final quiz) • Write a function called myMax, which finds the numbers with the highest numerical values in a matrix. Note: You may not use the MATLAB functions 'max' or ‘sort’ in your code. You need to write the algorithm. • The function should get a numeric data matrix as input and a string specifying whether the function should return a vector of the maximal values of each row or column of the input matrix. The function may also write display the maximal number in the entire array in the command window. • More specifically: • The two obligatory inputs of the function are the data matrix, and a string that can have two values: • If the value is 'row' - the function should return a vector of the maximal values of each row of the input matrix. • If the value is 'col' - the function should return a vector of the maximal values of each column of the input matrix. • The user can also call the function with an optional 3rd input argument, the string ‘print’. In this case, the function also prints in the command window a message that displays the maximum number in the entire matrix. • Example: "The maximum number in the matrix is 5" • BONUS: In cases that the user calls the function with illegal inputs it should return an empty array as its output. The illegal inputs you should check for are: empty data matrix as the 1st input, improper 2ndand 3rd input arguments (not the string 'row'/'col‘ or ‘print’).