Using function handles for inputs
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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?
0 Commenti
Risposte (2)
Guillaume
il 29 Gen 2015
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 Commenti
Guillaume
il 29 Gen 2015
Modificato: Guillaume
il 29 Gen 2015
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
il 29 Gen 2015
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.
0 Commenti
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!