Newton Iteration using symbolic function
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Bjorn Gustavsson
le 7 Déc 2021
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 commentaires
Voir également
Catégories
En savoir plus sur Assumptions dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!