-2

If I have a code like this

funk=@(x) x2-4;     
dfunk=@(x) 2*x;   

xk=4; 

for i = 1:5    
   xk+i= xk-funk(of what? xk or @(x) x2-4) / dfunk( same problem here);    
 end

I do not know what am I supposed to write in brackets it is supposed to be Newton Raphson method. Thanks for help

ucMedia
  • 4,105
  • 4
  • 38
  • 46
VeronikaS
  • 151
  • 4
  • You may want to take a look at the implementation of the Newton-Raphson method. Since you wrote `funk = @(x)` one can assume it is func(x) and since you update x for every iteration one can assume it need to be x_i. Apart from this additions are not allowed on RHS (but I assume this is pseudo code for xk_i?). You do neither update xk in the loop. This have to be done. Try `xk = xk - funk(xk) ...` If you want to keep the old values of `xk`, store them separately in a vector. Also it is not `x2`. It is `x.^2`. Next time you write a question, try to spend some effort on not writing pseudo code. – patrik Sep 07 '16 at 08:19

1 Answers1

0

You should not add i to your xk in the for loop. As Newton's Metod generates a series which converges to a root of the funktion the +i only operates on the indices of the series.

Your code should look like this.

funk = @(x) x^2-4;
dfunk = @(x) 2*x;
xk = 4;
for i=1:5
    xk = xk - funk(xk)/dfunk(xk)
end

Anyway I would not recommend to use a fixed condition like i=1:5 but something like

TOL = 10e-4;
DIFF = 1;             % something larger than TOL
funk = @(x) x^2-4;
dfunk = @(x) 2*x;
xk = 4;

while (DIFF > TOL)
   aux = xk - funk(xk)/dfunk(xk);
   DIFF = abs(xk-aux);
   xk = aux;
end
StefanM
  • 797
  • 1
  • 10
  • 17