Using function handles for inputs

조회 수: 6 (최근 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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by