Using function handles for inputs

13 ビュー (過去 30 日間)
mm
mm 2015 年 1 月 29 日
編集済み: Guillaume 2015 年 1 月 29 日
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 件)

Guillaume
Guillaume 2015 年 1 月 29 日
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
Guillaume
Guillaume 2015 年 1 月 29 日
編集済み: Guillaume 2015 年 1 月 29 日
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)

サインインしてコメントする。


Star Strider
Star Strider 2015 年 1 月 29 日
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.

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by