|
|
|||
![]() |
Department of Engineering |
| University of Cambridge > Engineering Department > computing help > programs > matlab |
Sometimes (for instance when using the ODE function ode23)
you need to pass the name of a function as an argument to another function.
The context of a function call affects which function is
actually called - if you pass the function name "fun" to
ode23, ode23 might not use the "fun.m" file you expect - for example, the ode23 function may have
a sub-function or private function called "fun"
(see Finding Matlab functions for details).
This is a situation where 'function handles' are useful. Rather than
pass the name 'fun' you pass @fun. This ensures
that the "fun" routine that would be called from your own code
is the one that ode23 will call.
Once you create a function handle, it is not affected by subsequent changes to your MATLAB environment - changing the PATH or adding other functions with the same name as the original won't make a difference.
The MATLAB feval command has to be used to run the function in a function handle. The syntax for using this command is
feval(fhandle, arg1, arg2, ..., argn)
function foo
% Call subfoo1 twice, first giving a function name, then a function handle
subfoo1('subfoo2')
fhandle=@subfoo2;
subfoo1(fhandle)
% A subfunction
function subfoo1(funname)
disp('I am subfoo1.')
if isa(funname,'function_handle')
disp('You gave me a function handle. Calling ''functions'' on it gives')
functions(funname)
str=func2str(funname);
else
disp('You gave me a function name.')
str=funname;
end
disp(['I am going to call ' str])
feval(funname)
% Another subfunction
function subfoo2
disp('I am subfoo2')
| | computing help | Matlab | |