How to use fzero and choose correctly initial guess?

Hi,
May I know how to solve the following equation with fzero and get two numbers: -2 and +2.
When I used the following code, it returned x=-2
fzero(@(x) x^2-4,0)
And this returned x=+2
fzero(@(x) x^2-4,1)
And furthermore, how can I choose correctly the initial guess number? I found that the answer will depend on the initial guess.

 Accepted Answer

Whenever I have a function I want to use fzero with, I plot it to see how many zeros it has and about where they are. I then choose my initial estimates based on that.
A more mathematically correct approach involves taking the vector you want the zeros of, then multiplying it by a one-position circularly-shifted version of itself, using the circshift function. This produces negatives at the zero crossings that are easy to test for and determine the indices of using the find function. I then use the x-values at those indices as the initial estimates. The initial estimates don’t have to be perfect, just close enough. If there are several zero-crossings, you will get several answers from fzero. It is up to you to choose the ‘correct’ zeros.

4 Comments

Hi,
Thanks for your reply.
My pleasure!
EDIT —
This illustrates the idea:
x = linspace(-10,10); % Interval To Evaluate Over
f = @(x) x.^2-4; % Function
fx = f(x); % Function Evaluated Over ‘x’
cs = fx.*circshift(fx,-1,2); % Product Negative At Zero-Crossings
xc = x(cs <= 0); % Values Of ‘x’ Near Zero Crossings
for k1 = 1:length(xc)
fz(k1) = fzero(f, xc(k1)); % Use ‘xc’ As Initial Zero Estimate
end
The ‘xc’ variable contains the approximate zero-crossings created by multiplying the value of the function by a version of itself circularly shifted by one position in ‘cs’. Those points are then the initial estimates for the fzero call in the loop. This will detect all of the roots on the interval defined by ‘x’.
The one problem with this simple idea is that the ‘cs’ and ‘xc’ assignments it may also detect a zero-crossing at the end of a periodic sequence that is not actually a root, as well as singularities that are not roots, for instance in the tan function over several cycles. It is always good to plot the function you are working with over the region-of-interest, and make allowances in your code for false-positives in ‘cs’ and ‘xt’ due to these effects.
Great thanks!. It makes me easier to understand your means.
My pleasure! I apologise for not including that in my original answer.

Sign in to comment.

More Answers (0)

Asked:

on 26 Oct 2014

Commented:

on 27 Oct 2014

Community Treasure Hunt

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

Start Hunting!