From: catrina on
Hi everyone,

I would be grateful if you could help me with this basic question as I am very new to MATLAB.

I need to find all the roots of some equation in the interval [o, pi], so I wrote the code below and it does work fine and give the right result, but the problem is that I need to find all the roots in the interval and the code nly giving me the root which close to the the intial value.

How can I update the code below to find all the roots?? may be I need extra while statemnet??

function [root, numIter] = newton_simple(func,dfunc,x,tol)
N = 3
format long g
% while(root < pi)
if nargin < 7;
tol = 1.0e-8;
for numIter = 1:500
dx = -feval(func,x,N)/feval(dfunc,x,N);
x = x + dx;
if abs(dx) < tol
root = x
% return
end
end
root = NaN;
end
%%%%%%%%%%%%
function y = dfunc(x,N)
% N = 3;
global lampda
% lampda = 0.2;
y = (N+1)*lampda^(-0.5)*cos((N+1)*x)-2*N*cos(N*x)+(N-1)*lampda^(0.5)*cos((N-1)*x);
%%%%%%%%%%%%%%
function y = func(x,N)
% N = 3;
global lampda
% lampda = 0.2;
y = lampda^(-0.5)*sin((N+1)*x)-2*sin(N*x)+lampda^(0.5)*sin((N-1)*x
%%%%%%%%%%%%%%%
the code above seems to give only one root, where I want to find all
the roots in the interval [0,pi]


I tried to do this by adding while(root < pi), befor if stataemnt, but
it is still giving me only one root


appreciate ur help


thanks
From: Doug Weathers on
"catrina " <mohammed.saad37(a)yahoo.com> wrote in message <i2a7u8$oob$1(a)fred.mathworks.com>...

>the problem is that I need to find all the roots in the interval and the code nly giving me the root which close to the the intial value.

A root is where the function is equal to zero.

For a well-behaved continuous function, this will be between a positive value of the function, and a negative value of the function.

You could use a for loop to step through the region of the X axis you are interested in and test the function value at each X. As soon as you see the sign of the function change, you know there's a root between the previous and current value of x. You can use X as a guess for your root finder.

You are not guaranteed to find all the roots this way, but you'll find the easy ones.

step = 0.01; % make this smaller to find more roots
guess = [];
prev= func(a);
for x = a:step:b
curr = func(x);
if sign(prev) ~= sign(curr)
guess = [guess x];
end
prev = curr;
end

You could also just plot the function, look at where the roots are, and guess where the roots are by eye, then use those as your guesses.

HTH,

Doug