Newton Iteration using symbolic function
조회 수: 5 (최근 30일)
이전 댓글 표시
i have write a code for newton iteration method as below;
i got answers in "x" domain. i wanted answer in real numbers

c=2;
syms x
f=x^2-c;
fdx=diff(f)
if fdx==0
disply('Output failure Stop the procedure')
else
x=input('initial condition ='); %initial condition
n=input('Number of iterations = '); %number of iterations
for i=1:n;
x=x-f/fdx;
vpa(x)
end
end
댓글 수: 0
답변 (1개)
Bjorn Gustavsson
2021년 12월 7일
Since you use symbolic variables and do the calculations symbolically you will get a symbolic answer.
Here you should convert your function, f, and its derivative to functions. You could do that with the matlab-function matlabFunction. Perhaps something like this:
c=2;
syms x
f=x^2-c;
fdx=diff(f)
if fdx==0
disply('Output failure Stop the procedure')
else
F = matlabFunction(f); % Here we create a dynamical function out of your symbolic expression
dfdx = matlabFunction(fdx); % and its derivative.
x = input('initial condition ='); %initial condition
n = input('Number of iterations = '); %number of iterations
for i1 = 1:n;
x = x - F(x)/dfdx(x); % Call function and its derivative at the point x
X(i1) = x; % Just to save away all points along the iteration
end
end
You should have a thorough look at the help and documentation for function_handle. In this simple case it works out automatically. However, you should preferably not rely on matlabFunction creating functions with some specific ordering of the input parameters, therefore you better check that for real-world use.
HTH
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!