Filter löschen
Filter löschen

Empty output with newtons method

3 Ansichten (letzte 30 Tage)
ahmed saheed
ahmed saheed am 7 Nov. 2020
Kommentiert: ahmed saheed am 7 Nov. 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

Akzeptierte Antwort

Samuele Sandrini
Samuele Sandrini am 7 Nov. 2020
Bearbeitet: Samuele Sandrini am 7 Nov. 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).

Weitere Antworten (0)

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by