Newton Method Matlab code

10 views (last 30 days)
Malcolm Kevin
Malcolm Kevin on 25 Jan 2021
Answered: Vishesh on 3 Oct 2022
function approximation = newtonsMethod( fnc, x0, delta )
maxnumIter = 100;
n = 0; % Initialize iteration counter.
syms fp; % derivative
fp = diff(fnc);
c = x0;
while ( (abs(subs(fnc,c))>tol) & (n < maxnumIter) )
c = double(c - subs(fnc,xcur)/subs(fp,c));
n = n+1;
end
if (n<100)
c(end);
disp('num_iter f(x) fprime(x) ')
disp('________________________________________________________________________________________')
end
for i=1:n
fprintf('%d \t %20f \t %20f\n',i ,fnc (c(i)),fp (c(i)))
end
if( abs(subs(fnc,c))> delta)
disp(['Warning: Tolerance not met after ' num2str(maxnumIter) ' iterations.']);
end
approximation = c;
Above is a code I attempted for newton method. I was a bit confused about how to print out a table of values for iteration number, x, f(x), f'(x). I tried to add a "if" statement below "while" and use display, but I got error like this
Array indices must be positive integers or logical values.
Error in sym/subsref (line 870)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in newtonsMethod (line 32)
fprintf('%d \t %20f \t %20f\n',i ,fnc(c(i)),fp(c(i)))

Answers (1)

Vishesh
Vishesh on 3 Oct 2022
  1. In the above code, you haven't stored the "c" values anywhere and you are trying to access the "c" values in "fprintf('%d \t %20f \t %20f\n',i ,fnc(c(i)),fp(c(i)))".
  2. In your code, "c" is just a variable but you are trying to access it as an array.
  3. Below is the modified code where i am storing the "c" values (which is "x" values) in "x_values".
function approximation = newtonsMethod( fnc, x0, delta )
maxnumIter = 1000;
n = 0; % Initialize iteration counter.
syms fp; % derivative
fp = diff(fnc);
c = x0;
x_values=[x0];
while ( (abs(subs(fnc,c))>delta) && (n < maxnumIter) )
c = double(c - subs(fnc,c)/subs(fp,c));
x_values=[x_values c];
n = n+1;
end
if (n<100)
c(end);
disp('num_iter f(x) fprime(x) ')
disp('________________________________________________________________________________________')
for i=1:n
fprintf('%d \t %20f \t %20f\n',i ,fnc (x_values(i)),fp (x_values(i)))
end
end
if( abs(subs(fnc,c))> delta)
disp(['Warning: Tolerance not met after ' num2str(maxnumIter) ' iterations.']);
end
approximation = c;
end

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!