Newton's method - how to make the computational performance faster?

3 views (last 30 days)
I have used a while loop in the algorithm. Once the absolute error is less than the specified tolerance (tol), the while loop stops and the function is expected to output one solution, even though many solutions exist. I have tried x^3 + 8x -18=0 with a starting guess 2. It should take two iterations to obtain the solution, but I cannot figure out why the computational perfomance is very slow when executing the function.
function moisolver
syms x
func=input('Enter the function f(x) which is equal zero:');
xn=input('Enter your initial guess:');
% The function func is switched to a function handle class
Dfunc=jacobian(func,x);
Dfunc=matlabFunction(Dfunc);
% The derivative dfuncd is switched to a function handle class
dfuncd=diff(func);
Dfuncd=jacobian(dfuncd,x);
Dfuncd=matlabFunction(Dfuncd);
% The tolerance is defined. The abs_error, counter and the vector
% storing the approximated solutions during the iteration process, are
% initialized
tol=10^(-1);
abs_error=1;
counter=1;
vec=xn;
while abs_error>=tol
counter=1+counter;
% xn is the iterative solution
xn=xn-Dfunc(xn)/Dfuncd(xn);
% An expanding vector veczero is added with xn
veczero=zeros(1,counter)+xn;
% The former solutions are redefined in veczero. Notice that the
% last element in veczero is defined as the last obtained solution
veczero(1:counter-1)=vec;
% vec is redefined
vec=veczero;
% The absolute error is calculated
abs_error=abs(vec(end)-vec(end-1));
end
solution=vec(end);
fprintf('The solution is %.2f.\n',solution)
fprintf('The computer generated %d iterations to obtain the solution.\n',counter)

Accepted Answer

Matt J
Matt J on 24 Dec 2012
Edited: Matt J on 24 Dec 2012
If the goal is to find a root of func, then the update formula for Newton's method should be
xn=xn-func(xn)./Dfunc(x)
This method of accumulating the solutions
veczero=zeros(1,counter)+xn;
is also hurting you in multiple ways. You should be pre-allocating memory for vec prior to the loop. You should also not be using vector addition to append xn to vec, when a scalar assignment operation will do the same thing much less expensively.
vec(counter)=xn;
  4 Comments
bym
bym on 24 Dec 2012
seems to work fine for me... (R2008b)
matlabFunction(diff(func))
ans =
@(x)3.*x.^2+8

Sign in to comment.

More Answers (0)

Categories

Find more on Interpolation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!