Using function handles for inputs

So I'm having a problem with my code where I'm supposed to use a function of f (an anonymous function handle) as an input into my function and I'm not really sure how to do that.
My function is
f=@(phi) (1-phi)./((phi-.32).^.32)
and I'm not given the value of phi
so far my function header looks like this:
function [ xr, epsA, Niter ] = secant( f, x0, x1, epsMax )
where f is supposed to be my function, and the other inputs are given values
If I run the code without defining f I just get eh error "Undefined function 'secant' for input arguments of type 'function_handle'."
So my question is, how do I use function handles as inputs?

回答(2 个)

The most common reason for getting Undefined function xxxx for input argument of type yyyy is because function xxxx is not on matlab path.
Most likely, your function is not on the path. Check the output of
which secant

2 个评论

mm
mm 2015-1-29
编辑:mm 2015-1-29
by on the path do you mean is my function saved in my current folder? If that is your question then it is saved there but I'm still unsure of how to use function handles as inputs
By 'on the path' I mean that is currently visible to matlab. The only way to check this is by using:
which secant
Saving the function in your current folder should indeed put the function on the path, but until you've checked with which you can't be sure.
As for using function handles, you use them exactly you use normal functions, e.g.:
function d = difference(f, x0, x1)
%f: function handle
%x0 and x1: points at which to evaluate the function
d = f(x1) - f(x0); %use function handle just like a normal function
end
Which you call with
f=@(phi) (1-phi)./((phi-.32).^.32);
d = difference(f, 2, 1)

请先登录,再进行评论。

Using function handles as inputs is fairly straightforward. Pass them just as you would any other argument.
For example, to take the simple numerical derivative of your ‘f’ function, then plot both:
f=@(phi) (1-phi)./((phi-.32).^.32); % Function
df = @(f, x) (f(x+1E-8) - f(x))./1E-8; % Derivative
phi = linspace(0,1);
figure(1)
plot(phi,f(phi), phi,df(f,phi))
grid
I used anonymous functions here for convenience, but the same idea will work for your function.

类别

帮助中心File Exchange 中查找有关 MATLAB 的更多信息

提问:

mm
2015-1-29

编辑:

2015-1-29

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by