Borrar filtros
Borrar filtros

Empty output with newtons method

2 visualizaciones (últimos 30 días)
ahmed saheed
ahmed saheed el 7 de Nov. de 2020
Comentada: ahmed saheed el 7 de Nov. de 2020
Hi all
im new to matlab and im attempting to create a newtons method calculator. I keep getting an empty square bracket as an output. Can you kindly look into my code to see where the problem arises:
function approx = newton(f,nmax,tol,x0)
i = 1;
while (i<nmax)
x1 = x0 - f(x0)./diff(f(x0));
if (abs((x1 - x0)/x1) < tol)
break
end
i = i + 1;
x0 = x1;
disp(x1)
end
approx = x1;
end
Thank you

Respuesta aceptada

Samuele Sandrini
Samuele Sandrini el 7 de Nov. de 2020
Editada: Samuele Sandrini el 7 de Nov. de 2020
Hi, the problem is in this line:
x1 = x0 - f(x0)./diff(f(x0));
because f(x0) is a number and the function diff doesn't return the derivative of f, but of a vector X it returns a vector containg the differences between adjacent elements like this (Y =diff(X)= [X(2)-X(1) X(3)-X(2) ... X(m)-X(m-1)]). So, if f(x0) is a number, diff(f(x0)) it returns nothing ([]).
If you want to apply the Newton Method you have to know the derivative of f,and pass it as an input of function newton (newton(f,df,nmax,tol,x0)), and in that point you evaluate the derivative of f in x0 (you can compute it in symbolic way and then convert it in function handle using matlabFunction(df)).
However, your idea is not wrong, but is similar (but incorrectly implemented because you would need to divide it by (x1-x0) to have the derivative but you don't know x1 yet) to the Secant Method, that is used whenever the derivative of f is unknown or diffucult to compute: you substitute the derivative of f in x0 with an approximation that is the angular coefficient of the line passing between a node () and the previous one ():
so the algorithm became something like this:
where
Note that, in this case at starting point you have to pass not only one point x0 but also another one point x1 (Here an example of implemantation).

Más respuestas (0)

Categorías

Más información sobre Mathematics en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by