find zero of a custom function

12 views (last 30 days)
Paolo
Paolo on 5 Dec 2013
Commented: Brett Cooper on 16 Nov 2017
Hello, I would like to know if it is possible to use fzero for a custom function written using a script. For example: let us suppose I have defined a function f.m which takes 3 arguments f(x,y,z) I know the values of x and y and I want to find the value of z which returns the value of my function 0,
is it possible to use fzero ? if yes could you post a very simple example?
Thanks you Paolo
  1 Comment
Paolo
Paolo on 7 Dec 2013
Thanks Walter, just another question about fzero. I am trying to find the zero of the following inline function:
fun=inline('-Pt1+y+(zcb+(rate*tau2*y))')
where Pt1=0.999970474084335 zcb=0.005646500819616 rate=0.0056460 tau2=0.99722222222222
yres=fzero(@(y) fun(Pt1,tau2,rate,zcb,y),[0.2,1.0])
yres=0.994292181677045
but when I go to check the inline functionsubstituting the value of y with yres I get
val=-Pt1+yres+(zcb+(rate*tau2*yres))
val=0.005566388254360
while I was expecting a value quite close to 0
Any clue?
Thanks Paolo

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 7 Dec 2013
First of all, do NOT use inline functions. They are slow, a hack given to us in the days before function handles were provided.
Pt1=0.999970474084335;
zcb=0.005646500819616;
rate=0.0056460;
tau2=0.99722222222222;
% a better fun. See that since all parameters but
% y are known, the function handle uses those values.
% I could also have written fun as a function of 5
% parameters, and then reduced it to a single variable
% function using a function handle in the call to zero.
fun = @(y) -Pt1+y+(zcb+(rate*tau2*y));
Next, plot the function!!!!!!!!!! Always do this.
ezplot(fun)
grid on
As you can see, there is clearly a root, just under 1.
ysol = fzero(fun,[0,2])
ysol =
0.988756958482095
fun(ysol)
ans =
-1.04083408558608e-17
Anyone who claims this was not a root should learn to read scientific notation. So I'm not at all sure what you did wrong, but it looks like you used some inaccurate value in the computation.
  2 Comments
Paolo
Paolo on 7 Dec 2013
Thanks John, that's perfect!
Brett Cooper
Brett Cooper on 16 Nov 2017
Hello, would this method also work for a 2D custom function to find its zeros? In my case, I expect the function to be zero on a line...

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 5 Dec 2013
fzero( @(z) f(x, y, z), InitialGuessGoesHere )

Tags

Community Treasure Hunt

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

Start Hunting!