4
$\begingroup$

How to find all roots of an equation in Matlab? I tried and it gave me just one of the roots.

For example: my equation is $F(x)=0$ where

 F(x) = (cos(7*x)).*exp(-2*x.^2).*(1-2*(x.^2)) 
$\endgroup$
  • $\begingroup$ Please check your equation - I don't think that is valid Matlab syntax (lone dot). $\endgroup$ – Federico Poloni Dec 29 '14 at 10:15
  • 2
    $\begingroup$ What did you try in MATLAB? $\endgroup$ – Doug Lipinski Dec 29 '14 at 13:57
9
$\begingroup$

Before trying to find all of the roots of this function in MATLAB I think it's worth understanding that it has infinitely many roots due to the inclusion of the $\cos()$ term. Additionally, it is easy to find the roots of the function analytically in this case:

The roots are defined by $$ \cos(7x)\cdot \exp(-2x^2)\cdot (1-2x^2) = 0. $$ So we have $$ \cos(7x)=0\text{ or }\exp(-2x^2)=0\text{ or }(1-2x^2) = 0, $$ which gives $$ x = \left\{\left(n+\frac{1}{2}\right)\dfrac{\pi}{7}: n\in\mathbb{Z}\right\} \cup \emptyset \cup \left\{\pm\sqrt{1/2}\right\}. $$

To answer your question in a more general sense, a simple way to look for more than one root in MATLAB would be to use the fzero function with many different starting guesses over some pre-defined range. This is not guaranteed to find all zeros, but by passing an interval to fzero you can at least guarantee that you will find zeros where the function changes sign on that interval. By choosing small enough intervals you can obtain very good results.

For example, the following code will find all the roots of your function on the interval [-10,10]. If any roots were missed you could increase N to use more (smaller) starting intervals for fzero. Note that this will only find roots where the sign changes.

F = @(x) cos(7*x).*exp(-2*x.^2).*(1-2*x.^2);
interval = [-10, 10];
N = 500;
start_pts = linspace(interval(1),interval(2),N);
found_roots = [];
for i=1:numel(start_pts)-1
    try
        found_roots(end+1) = fzero(F,[start_pts(i),start_pts(i+1)]);
    end
end

% Plot results:
figure, hold on
fplot(F,interval,1e-4)
plot(found_roots,zeros(size(found_roots)),'rx')

*Note that this method (and most numerical methods) will not work for $|x|$ greater than ~19.3 for this function. This is because $\exp(-2(19.4)^2)$ equals 0 with double precision numbers.

$\endgroup$
4
$\begingroup$
syms x
eq=cos(7*x)*exp(-2*x^2)*(1-2*x^2);
solve(eq==0,x)

ans =

      pi/14
  2^(1/2)/2
 -2^(1/2)/2

Or if your version of Matlab is recent, you can do

evalin(symengine,'solve(cos(7*x)*exp(-2*x^2)*(1-2*x^2)=0,x)') 

{-2^(1/2)/2, 2^(1/2)/2} union Dom::ImageSet(pi/14 + (pi*k)/7, k, Z_)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.