CS100J, Fall 2001 Mon 12/4 Lecture 26 ------------------------------------------------------------------------------- Announcements: + see recent online Web announcements (recent blizzard...) + regular consulting ends after 12/7 + final consulting hours: MTW (12/10-12/12) + Prelim 3 regrades due by last shift on 12/12 + Project 6 regrades due by 4pm 12/14 in UPSON 303 (see Laurie Buck's hours) + makeup exam 12/6, 7:30-9:30 (Beth Howard will email the location) + final exam info posted in Exams-->Final (read it!) + review material for final in Exams-->Review Final + special review on Weds 12/5 7:30 in Upson B17 ------------------------------------------------------------------------------- Approach 1: script M-files + script - the M-files you've written so far - collection of commands that you could have entered at the prompt + write "little" subprograms + store them in different m-files + call the programs when necessary, but ensure path is set - invoke by using the script name as a command - use EVAL: ex) >> eval('scriptname') + shares all variables that could be entered at the prompt + see scripthelp.txt ex) restore.m s1.m s2.m +--------+ +----------+ +--------+ | clear | | restore | | s1; | | clc | | x=1; | | x=x+1; | +--------+ | pause | +--------+ +----------+ >> s2; x; restore Output? ------------------------------------------------------------------------------- Approach 2: Function M-files + similar to scripts, but contain functions (resemble methods) + how to write your own functions FUNCTION [output_args] = name(input_args) H1 comment line accessed by LOOKFOR comments accessed by HELP statements (optional) RETURN (optional) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- Syntax continued: + name: name of function - similar rules for naming as variables - see help pages for additional rules + input_args: names of variables used inside function - visible only to function - not used from "outside", nor visible to "outside" why? each function has a separate workspace with its own names! - may have zero or many inputs + output_args: names of variables to return to caller - the value(s) of the outputs are "sent" back to the expression that invoked the function - may have zero or many outputs + keywords: function, return ------------------------------------------------------------------------------- Handy Rules (from MASTERING MATLAB): + you should give the function file and its the name the same name + function names are used up to 31 chars + begin names with lowercase letter and follow other variable naming rules + the H1 line is FUNCTION DECLARATION LINE (for LOOKFOR) + following comments are for HELP + BODY of function are the statements + code inside function stops when reaching the last statement or RETURN (RETURN acts like a BREAK because you can exit function "early") + use ERROR to abort execution: example) if length(val) > 1 error('wrong!') end see HELP WARNING to flag the user but continue with execution ------------------------------------------------------------------------------- Example) Your own function for adding, add.m: +-----------------------------------------+ | function x = add(a,b) | | % ADD(A,B) returns the sum of A and B | a and b are __________ | % ADD(A,B) adds A and B together. | | % This function is just a simple demo. | x is _________________ | x = a+b; | +-----------------------------------------+ At command window prompt: >> add(1,2) ans = >> add(1,2) - add(1,2) ans = >> add(1,2)*sqrt(16) ans = ------------------------------------------------------------------------------- Scope: + range or location where a name is visible (or not) + MATLAB partitions memory into WORKSPACES - each workspace has its own names (variables, scripts, functions) - the command window provides one workspace - each function has a different workspace + variables of a workspace are not shared in other workspaces - variables are called LOCAL VARIABLES when not shared] - use GLOBAL to get around this, but usually discouraged ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- + Example) design function to swap values In file called swap.m: +------------------------------+ | function [x,y] = swap(a,b) | | x = b; | | y = a; | +------------------------------+ In command window: >> a=1;b=2; >> [a b] = swap(a,b) >> a a = ____ >> b b = ____ Even shorter version: +--------------------------------+ | function ______ = swap(______) | +--------------------------------+ ------------------------------------------------------------------------------- Inputs and Outputs + can have as many inputs and outputs as you want - may even have zero of either or both - MATLAB actually allows a call to a function with fewer inputs and outputs than required by the function, though you may run into trouble with too few inputs + can have different amounts of inputs and outputs ------------------------------------------------------------------------------- 1 input, 1 output: function v=y(x) v = x+1; >> y(1:2) ans = ------------------------------------------------------------------------------- multiple input, 1 output: function v=y(x1,x2) v=x1+x2; >> y(1,2) ans = ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- multiple inputs, multiple outputs: function [v,w] = y(x1,x2) v = x1+x2; w = x1.*x2; >> y(1,2) % assumes you mean just the FIRST output ans = >> z = y(1,2) % assumes you mean just the FIRST output z = >> [a b] = y(1,2) % now you get multiple outputs a = b = ------------------------------------------------------------------------------- no outputs: example 1) function y(x1,x2) x1+x2 >> y(1,2) ans = But did ans really get assigned? Which ans got assigned? ------------------------------------------------------------------------------- no inputs: function y() % could also say "function y" disp('hi'); >> y % you must enter with no "()" ans = ------------------------------------------------------------------------------- Subfunctions: + can put other functions in a function M-File + these functions are written below the first function + the first function is usually the name of the M-File and is visible to other functions in the same path + the other functions are called SUBFUNCTIONS - they are NOT visible to "outside functions" - they are strictly visible to the first function and other other functions in the same M-File ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- example) function x = blah(a,b) % Hi there, I'm glad you found me. % BLAH(A,B) isn't too interesting: % It adds vector A to B x = blah2(a,b); function y = blah2(a,b) % subfunction of blah y = 2.*a+b >> blah(1:2,2:3) ans = >> blah2(1:2,2:3) ans = ------------------------------------------------------------------------------- Function function: + function with an input argument the name(s) of other function(s) ex) ezplot('cos(x)') ezplot plots a function without having you to figure out other inputs + usually input names are strings function demofunfun % DEMOFUNFUN demonstration of function functions disp('Starting demo of function functions...'); name = input('Enter the name of a function as a STRING: '); % example: user enters $'cos'$ plotf(name,linspace(-10,10,10000)); function plotf(name,x) % evaluate the function with name $name$ with input $x$ % $feval$ evaluates a function with given inputs y = feval(name,x); % could also use less efficient $eval(string)$ which % evaluates $string$ as a script command % now do something interesting with the values plot(x,y); ------------------------------------------------------------------------------- Recursion: + function calls itself (Yes, MATLAB and other languages can do that!) function result = rsum(n) if n==1 result = 1; else result = n + rsum(n-1); end % Actually this case handled much quicker by MATLAB itself % sum(1:n) % could also do loop -------------------------------------------------------------------------------