필터 지우기
필터 지우기

Empty output with newtons method

조회 수: 2 (최근 30일)
ahmed saheed
ahmed saheed 2020년 11월 7일
댓글: ahmed saheed 2020년 11월 7일
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

채택된 답변

Samuele Sandrini
Samuele Sandrini 2020년 11월 7일
편집: Samuele Sandrini 2020년 11월 7일
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).

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by