MATLAB Functions – Part II Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

Slides:



Advertisements
Similar presentations
Lecture 5.
Advertisements

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
MATLAB Optimization Greg Reese, Ph.D Research Computing Support Group Miami University.
CIS100 Test 2 Review REACH CRC © 2011 REACH CRC. All Rights Reserved.Spring 2011.
Modular Programming With Functions
A MATLAB function is a special type of M-file that runs in its own independent workspace. It receives input data through an input argument list, and returns.
REACH CRC © 2011 REACH CRC. All Rights Reserved.Fall 2011.
Advanced use of functions Anonymous functions function handles subfunctions and nested functions.
MATLAB Examples. CS 1112 MATLAB Examples Find the number of positive numbers in a vector x = input( 'Enter a vector: ' ); count = 0; for ii = 1:length(x),
Introduction to C Programming
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
MATLAB Cell Arrays Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University.
Introduction to C Programming
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
Introduction to Python
Lists in Python.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 6.
A First Book of ANSI C Fourth Edition
How to think through your program [ principles of good program design ] Rachel Denison MATLAB for Cognitive Neuroscience ICN, 13 December 2007.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Using Client-Side Scripts to Enhance Web Applications 1.
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Microsoft Office 2007 Intermediate© 2008 Pearson Prentice Hall1 PowerPoint Presentation to Accompany GO! With Microsoft ® Office 2007 Intermediate Chapter.
Digital Image Processing Lecture10: MATLAB Example – Utility M-functions for Intensity Transformations.
MATLAB Harri Saarnisaari, Part of Simulations and Tools for Telecommunication Course.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Flow Control and Functions ● Script files ● If's and For's ● Basics of writing functions ● Checking input arguments ● Variable input arguments ● Output.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
A string is an array of characters Strings have many uses in MATLAB Display text output Specify formatting for plots Input arguments for some functions.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
While-end loop used when You don't know number of loop iterations You do have a condition that you can test and stop looping when it is false. For example,
Digital Image Processing Lecture 6: Introduction to M- function Programming.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Digital Image Processing Introduction to M-function Programming.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Repetitive Structures
EEE 161 Applied Electromagnetics
Scripts & Functions Scripts and functions are contained in .m-files
Outline Matlab tutorial How to start and exit Matlab Matlab basics.
User Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Use of Mathematics using Technology (Maltlab)
Functions In Matlab.
Loop Statements & Vectorizing Code
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Functions continued.
Matlab Basics.
Loop Statements & Vectorizing Code
Presentation transcript:

MATLAB Functions – Part II Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013

MATLAB Functions – Part II © Greg Reese. All rights reserved 2

3 Part I Write scripts Run MATLAB functions Write and run our own functions Use our functions in MATLAB plotting and optimization routines Write and use anonymous functions

4 Part II Document functions Detect number of inputs and outputs Subfunctions Nested functions

Documentation 5

6 To find out how to use a MATLAB function you type the command help function_name If you don't know function name, can look for important word in function description with lookfor word We can incorporate our functions in the MATLAB help system so help and lookfor work on custom code

Documentation 7 Look at results for MATLAB csvread() Try It 1.Type help csvread 2.Type lookfor 'comma separated' 3.Type type csvread

Documentation 8 >> help csvread CSVREAD Read a comma separated value file. M = CSVREAD('FILENAME') reads a comma separated value formatted file FILENAME. The result is returned in M. The file can only contain numeric values. M = CSVREAD('FILENAME',R,C) reads data from the comma separated value, etc. >> lookfor 'comma separated' lists - Comma separated lists. csvread - Read a comma separated value file. csvwrite - Write a comma separated value file. >> type csvread function m = csvread(filename, r, c, rng) %CSVREAD Read a comma separated value file. % M = CSVREAD('FILENAME') reads a comma separated value formatted file % FILENAME. The result is returned in M. The file can only contain % numeric values. % % M = CSVREAD('FILENAME',R,C) reads data from the comma separated value etc.

Documentation 9 help displays first group of contiguous comment lines in file Traditionally put right after function line Blank line breaks contiguous group –To display blank, put in line with only a percent sign

Documentation 10 Example – help output In file doc_check.m function [ result details ] = doc_check( fileName ) % DOC_CHECK Check a function m-file for correct documentation. % % Check that first comment has function name in capital letters and line % ends with a period, that every input and output parameter is documented, % etc. See explanation for "details" output parameter for full list >> help doc_check DOC_CHECK Check a function m-file for correct documentation. Check that first comment has function name in capital letters and line ends with a period, that every input and output parameter is documented, etc. See explanation for "details" output parameter for full list

Documentation 11 H1 or description line H1 = first line in help description lookfor uses this line –Make line descriptive of function –Include words user would most likely search for

Documentation 12 Example – lookfor output In file doc_check.m function [ result details ] = doc_check( fileName ) % DOC_CHECK Check a function m-file for correct documentation >> lookfor documentation doc_check - Check a function m-file for correct documentation. builddocsearchdb - Build documentation search database doc - Display HTML documentation in the Help browser. docsearch - Search HTML documentation in the Help browser.

Documentation 13 Suggestions for documentation H1 line Longer description of functionality Description of parameters Description of errors and how they're handled References

Documentation 14 H1 line suggestions File name in caps * End in period * Contain words likely to be searched for * MATLAB conventions. Don't know if they have functionality

Documentation 15 Longer description suggestions Name of algorithm, inputs and outputs, e.g. "Run's Reese's algorithm on the students in the class and produces a list of slackers and hard workers" Don't put in details spelled out further in documentation

Documentation 16 Parameter suggestions Definition Data type, e.g., scalar, vector, matrix, etc. –For vector, whether row, column or either Units Range –Be careful with > and ≥ Optional or required –Default if optional input

Documentation 17 Error suggestions Conditions that cause error State of output if error Internal state if error, e.g., "All open files in routine will be closed if there is an error" Error reporting mechanism –error() –errordlg() –Text of message

Documentation 18 Example In file doc_check.m function [ result details ] = doc_check( fileName ) % DOC_CHECK Check a function m-file for correct documentation. % % Check that first comment has function name in capital letters and line % ends with a period, that every input and output parameter is documented, % etc. See explanation for "details" output parameter for full list % % REQUIRED INPUT % fileName - name of file to check % REQUIRED OUTPUT % result - true if all items checked for are correct, false otherwise % OPTIONAL OUTPUT % details - all values true or false % details(1) - first word of first comment line is function name in caps % details(2) - first comment line ends with a period % etc. % ERRORS % If can't open or read file, calls error() fid = fopen( fileName ); % etc.

Documentation 19 Example - errors Output for help doc_check.m >> help doc_check DOC_CHECK Check a function m-file for correct documentation. Check that first comment has function name in capital letters and line ends with a period, that every input and output parameter is documented, etc. See explanation for "details" output parameter for full list REQUIRED INPUT fileName - name of file to check REQUIRED OUTPUT result - true if all items checked for are correct, false otherwise OPTIONAL OUTPUT details - all values true or false details(1) - first word of first comment line is function name in caps details(2) - first comment line ends with a period etc. ERRORS If can't open or read file, calls error()

Documentation 20 References Full citations for books, papers, etc. Web sites –URL –Date downloaded External codes used –MATLAB central –sourceforge.net –university

21 Documentation Questions?

Input / Output Arguments 22

Arguments 23 One function can have different numbers of inputs or outputs. Most MATLAB functions are like this fminbnd Find minimum of single-variable function on fixed interval Syntax x = fminbnd(fun,x1,x2) x = fminbnd(fun,x1,x2,options) [x,fval] = fminbnd(...) [x,fval,exitflag] = fminbnd(...) [x,fval,exitflag,output] = fminbnd(...)

Arguments 24 Why different number of inputs? Save caller from always entering argument that has commonly used value –e.g., delimiter in tokenizer usually a space Save caller from entering redundant arguments –e.g., correlation( x, y ) computes cross-correlation, for autocorrelation want correlation( x ) instead of correlation( x, x ) Allow caller to enter extra information if available –e.g., pass graph title to plotting routine

Arguments 25 In a function, get number of arguments passed to function with nargin Example – download scale.m function [ y expansion ] = scale( x, m, b ) % SCALE - linearly scale x so that y = m*x + b % x - unscaled data, row or column vector % Optional input arguments % m - slope, scalar ~= 0, default = 1 % b - y-intercept, scalar, default = 0 % % Required output % y - scaled data, same dimensions as x % Optional output % expansion - optional output, scalar, % expansion = (yMax-yMin)/(xMax-xMin)

Arguments 26 Typical verification of number of inputs function [ y expansion ] = scale( x, m, b ) % verify right number of input arguments if nargin == 1 m = 1; b = 0; elseif nargin == 2 b = 0; elseif nargin ~= 3 error( 'USAGE: y = scale( x, m, b ) m, b optional' ); end If missing inputs, set them If not max number of inputs, bail out

Arguments 27 Can verify data type % verify data type if ~isvector( x ) error( 'x must be a vector' ); elseif ~isscalar( m ) | ~isscalar( b ) error( 'm and b must be scalars' ); end

Arguments 28 Can verify range %verify range if m == 0 error( 'm must not be zero' ); end

Arguments 29 Try It >> y = scale( magic(3) ) ??? Error using ==> scale at 23 x must be a vector >> y = scale( 1:5, 2 ) y = >> y = scale( 1:5, 2, [ 5 6] ) ??? Error using ==> scale at 25 m and b must be scalars >> y = scale( 1:5, 2, 1, 5 ) ??? Error using ==> scale Too many input arguments. >> y = scale( 1:5, 2, 1 ) y =

Arguments 30 Why different number of outputs? Provide caller with less important computations –e.g., [R,P]=corrcoef(...) can return main result R (correlation coefficients) and optionally P (p-values) Provide caller with information about processing that took place Provide caller with information for use with other functions Provide caller with information about any errors

Arguments 31 Example – MATLAB fminbnd() [x,fval] = fminbnd(...) returns the value of the objective function computed in fun at x. [x,fval,exitflag] = fminbnd(...) returns a value exitflag that describes the exit condition of fminbnd: 1fminbnd converged to a solution x based on options.TolX. 0 Maximum number of function evaluations or iterations was reached. -1 Algorithm was terminated by the output function. -2 Bounds are inconsistent (x1 > x2). [x,fval,exitflag,output] = fminbnd(...) returns a structure output that contains information about the optimization: output.algorithmAlgorithm used output.funcCountNumber of function evaluations output.iterationsNumber of iterations output.messageExit message Main results Exit status Processing information

Arguments 32 In a function, get number of arguments requested by caller with nargout Example – scale.m function [ y expansion ] = scale( x, m, b ) % SCALE - linearly scale x so that y = m*x + b % x - unscaled data, row or column vector % Optional input arguments % m - slope, scalar ~= 0, default = 1 % b - y-intercept, scalar, default = 0 % % Required output % y - scaled data, same dimensions as x % Optional output % expansion - optional output, scalar, % expansion = (yMax-yMin)/(xMax-xMin) Continues on next slide

Arguments 33 Processing different number of outputs function [ y expansion ] = scale( x, m, b ) % compute main output if nargout == 1 y = m * x + b; elseif nargout == 2 y = m * x + b; expansion = ( max(y) - min(y) ) / ( max(x) - min(x) ); else error( 'USAGE: [ y expansion ] = scale( x, m, b ) m, b optional' ); end If optional output desired, compute it If not max number of inputs, bail out

Arguments 34 Try It >> scale( 1:5 ) ??? Error using ==> scale at 42 USAGE: [ y expansion ] = scale( x, m, b ) m, b optional >> y = scale( 1:5 ) y = >> y = scale( 1:5, 3 ) y = >> [ y ratio ] = scale( 1:5, 3 ) y = ratio = 3 >> [ y ratio z ] = scale( 1:5, 3 ) ??? Error using ==> scale Too many output arguments.

35 Arguments Questions?

Subfunctions 36

Subfunctions 37 A function m-file can contain more than one function. All functions other that the first one are called subfunctions. Subfunctions –Used mainly to carry out tasks that should be separated from primary function but unlikely to be used by other m-files – Help avoid having a lot of m-files – Override (used in place of) other functions of same name

Subfunctions 38 Subfunctions in a file Start with a function line End at next function line or at end of file Are only visible (usable) by the primary function or the other subfunctions Can come in any order as long as primary function comes first Cannot access variables in other subfunctions or in the primary function

Subfunctions 39 Example – download newstats.m function [avg, med] = newstats(u) % Primary function % NEWSTATS Find mean and median with internal functions. % From MATLAB help on subfunction n = length(u); % Note subfunction mean() gets called, not MATLAB's mean() avg = mean(u, n); med = my_median(u, n); function a = mean(v, n) % Subfunction % Calculate average. a = sum(v)/n; function m = my_median(v, n) % Subfunction % Calculate median. w = sort(v); if rem(n, 2) == 1 m = w((n+1) / 2); else m = (w(n/2) + w(n/2+1)) / 2; end

Subfunctions 40 Try It Call primary function >> [ av med ] = newstats( 1:11 ) av = 6 med = 6 Call subfunction >> med2 = my_median( 1:11, 11 ) ??? Undefined function or method 'my_median' for input arguments of type 'double'.

Subfunctions 41 Try It Verify overridden mean() called by putting line disp( 'In newstats mean' ); in subfunction mean() >> [ av med ] = newstats( 1:11 ) In newstats mean av = 6 med = 6

Subfunctions 42 Strange but True Although you can't access subfunctions from outside their file, you can get help on them! 1.Write normal help stuff for subfunction 2.On command line type help filename>subfunction_name where filename is the name of the file (without the.m) that the subfunction is in

Subfunctions 43 Try It After the function line for my_median put some help lines and print them by using the help command on the command line function m = my_median(v, n) % This is my median % Land that I love >> help newstats>my_median This is my median Land that I love

44 Subfunctions Questions?

Nested Functions 45 function1 function2 function3

Nested Functions 46 A nested function is a function defined within another function Nested functions often passed by function handle to functions that manipulate other functions – e.g., ezplot(), fminbnd(), etc. – Can be used instead of anonymous functions if function has more than one expression

Nested Functions 47 To define a nested function, just write it within another function Example function outer( a, b, c )... function inner( a )... end... end Nested function

Nested Functions 48 Nested functions Can be nested within other nested functions Cannot be inside any MATLAB program control statement, i.e., if, else, elseif, switch, for, while, try, or catch statement Must always be terminated by an end statement

49 Nested Functions MATLAB Help says: "M-file functions don't normally require a terminating end statement. This rule does not hold, however, when you nest functions. If an M-file contains one or more nested functions, you must terminate all functions (including subfunctions) in the M-file with end, whether or not they contain nested functions."

Nested Functions 50 You can call a nested function From the level immediately above it. (In the following code, function A can call B or D, but not C or E.) From a function nested at the same level within the same parent function. (Function B can call D, and D can call B.) From a function at any lower level. (Function C can call B or D, but not E.) You can also call a subfunction from any nested function in the same M-file. function A(x, y) % Primary function B(x, y); D(y); function B(x, y) % Nested in A C(x); D(y); function C(x) % Nested in B D(x); end function D(x) % Nested in A E(x); function E(x) % Nested in D... end

Nested Functions 51 The scope of a variable is the range of functions that have direct access to the variable. When define a variable in a function, scope normally that function alone Calling function cannot access called function's variables A subfunction cannot access another subfunction's variables

Nested Functions 52 Big power of nested functions: A nested function has access to the variables in all functions in which it is nested

Nested Functions 53 A variable that has a value assigned to it by the primary function can be read or overwritten by a function nested at any level within the primary A variable that is assigned in a nested function can be read or overwritten by any of the functions containing that function

Nested Functions 54 Example – download and run nested_fibonacci.m function nested_fibonacci % primary function % nested function function sum = print_and_sum( ix ) if ix < 3 sum = 1; else % nested function can access "indexes" % variable in containing function sum = indexes(ix-1) + indexes(ix-2); fprintf( '%d = %d + %d\n', sum,... indexes(ix-1), indexes(ix-2) ); end indexes = 1:8; % apply print_and_sum to every element of numbers, % save results in a vector and display the vector fib = indexes ); fib end % end of nested_fibonacci

55 Nested Functions Questions?

56 The End