%------------------------------------------------------------------------------CS100J, Spring 2001
Tues 5/1
Lecture 27
%------------------------------------------------------------------------------
% This file really isn't useful as an ENTIRE MATLAB script. You
% need to cut and paste the functions inside to see how they work.
%------------------------------------------------------------------------------
% FUNCTIONS
% How to do? Special kind of M-File
% So, what's an M-file?
% + script M-Files (what we've seen so far)
% - these are not functions
% - set of instructions as if entered at prompt
% + function files
% - write code for doing function
% - many things in MATLAB are functions
% - $help$ finds help on functions
% - see path browser to see functions in M-Files
%------------------------------------------------------------------------------
% Syntax:
%
% $function$ [output_args] = name(input_args)
% H1 comment line accessed by $lookfor$
% comments accessed by $help$
% statements (optional)
% $return$ (optional)
%
%------------------------------------------------------------------------------
% example: put the following in a file called blah
% function x = blah(a,b)
% x = a+b
%
% From CW, make sure your path is set and call
% blah(1:2,1:3)
% ML will report ans = [2 5]
%
% Note: $function$ is a required keyword
%------------------------------------------------------------------------------
% How does this work?
% PASSING BY VALUE
% + ML passes values from code that calls (the sender) to
% the function (the receiver).
% + The variables called INPUT_ARGS "catch" and become those values.
% + INPUT_ARGS also called DUMMY VARIABLES
% - inside the function the dummy vars have values passed to them
% - the dummy vars's values remain until the function finishes
% - then their values go away (except if you use $persistent$)
% + the variables "passed into" dummy vars do not change value in
% "calling" code
%------------------------------------------------------------------------------
% example:
% >> v=1;w=2;
% >> z = blah(v,w)
%
% ML looks for blah M-File. Then, values of $v$ and $w$ copied into $blah$'s
% dummy vars $a$ and $b$. But, $v$ and $w$ never change.
%
% $blah$ adds the values of $a$ and $b$ and stores the result in $x$ which is
% a LOCAL VARIABLE because it only exists in $blah$. Local variables only have
% values when a function is activated. The Command Window workspace does not
% even "know" that the local vars exist.
%
% $function x = blah(a,b)$ causes the values of $a$ and $b$ to be added and
% stored in $x$. Because $x$ appears after $function$, ML knows to RETURN the
% value of $x$.
%
% Returning means sending a value back to the code that called the function.
% ML effective "replaces" the calling code with the value sent back.
%
% So, $z$ becomes the value 3. If you get stuck, think $sqrt$. Imagine saying
% $z = sqrt(4)$. This statement makes $z$ become 4.
%
%------------------------------------------------------------------------------
% example) design function to swap values
% function [x,y] = swap(a,b)
% x = b;
% y = a;
% call in CW)
% >> a=1;b=2;
% >> [a b] = swap(a,b)
%
% even shorter: function [b,a] = swap(a,b)
%------------------------------------------------------------------------------
% I/O
% + can have zero input, zero outputs
% (see above)
% + can call functions with fewer inputs, outputs than required
% >> [a] = swap2(a,b) matches to just 1st output arg (left to right)
% + function does have to assign values to output args
%------------------------------------------------------------------------------
% Scope (where things are accessible from)
% The main workspace (Command Window) and other functions cannot "see" into
% another function unless you program it that way.
%
% So, local/dummy vars are unknown outside of functions.
% So, you may use the same variable names without a conflict.
% To have a variable known from "inside" known also "outside" use $global$
%------------------------------------------------------------------------------
% WORKSPACE
% + means portion of memory that's perform commands and storing information
% + local variables are not shared in other workspaces
% + use $global$ to get around this, but usually discouraged
%------------------------------------------------------------------------------
% Handy Rules (from MASTERING MATLAB, p144, on reserve)
% + you should name function file and name the same name
% + function names up to 31 chars
% + begin names with 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 $warning$ to flag the user but continue with execution
%------------------------------------------------------------------------------
% Functions calling other things
% + functions can call scripts which will activate in function's workspace
% (run as if the function were the command window)
% + local functions (SUBFUNCTION)
% - put function inside same file as another function
%
% 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
%
% From CW: >> blah(1:2,2:3) -> [4 7]
%------------------------------------------------------------------------------
% Rules for args:
% + Can have zero to many input&output args
% + "Can call function with fewer inputs and outputs than required by function"
% (actually, you may run into trouble with fewer inputs, but fewer outputs
% works OK)
%------------------------------------------------------------------------------
% 1 output, 1 input
% function v=y(x)
% v = x+1;
%
% >> y(1:2)
% ans = 2 3
%------------------------------------------------------------------------------
% multiple inputs
% function v=y(x1,x2)
% v=x1+x2;
%
% >> y(1,2)
% ans = 3
%------------------------------------------------------------------------------
% 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 = 3
% >> z = y(1,2) % assumes you mean just the FIRST output
% z = 3
% >> [a b] = y(1,2) % now you get multiple outputs
% a = 3
% b = 2
%------------------------------------------------------------------------------
% no outputs
% function y(x1,x2)
% x1+x2
%
% >> y(1,2)
% ans = 3
%
% another example)

% Question: What happens if there are NO output variables and...
% the function has output?

function nooutputs(x1)
x1+1
x1+2
x1+3

% Sample session:
% >> nooutputs(0)
%
% ans =
%
% 1
%
%
% ans =
%
% 2
%
%
% ans =
%
% 3
%
% >> ans
% ??? Reference to a cleared variable ans.
%
% >> x = nooutputs(0)
% ??? >
% |
% Missing variable or function.
%------------------------------------------------------------------------------
% no inputs
% function y() % could also say "function y"
%
% >> y % enter with no "()"...cool, huh?
% ans = 3
%------------------------------------------------------------------------------
% Search path for reference to script or function
% (See MASTERING MATLAB)
% + check if var is an assigned name in the current workspace
% + check if var is a built-in function
% + check if var is subfunction of the function file where var appears
% + check if var is a "private function" in M-File where var appears
% (beyond scope of CS100M for now)
% + check if var.m exists in current directory
% + check if var.m exists in path, from top to bottom
%------------------------------------------------------------------------------
% Creating your own toolbox
% + think of toolbox as a collection of functions
% + implications for software:
% ultimately, related procedures collected together
% almost all languages have this idea
% users of software use toolbox (or similar entity for other languages)
% later in Java, it's called the API....
% + how:
% create directory inside $toolbox$ directory
% put M-Files in the directory
% + see MASTERING MATLAB for more info
%------------------------------------------------------------------------------
% FUNFUN (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
% + see $function demofunfun$
% + see $fzero$ (I didn't use in project3, but could have...)
%
% example)
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 can do that!
% + see $rsum$ example
% + used in project3 as a kind of "repeat" if one script fails to work
%
% example:
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

%------------------------------------------------------------------------------