Newton Method Matlab code

10 次查看(过去 30 天)
Malcolm Kevin
Malcolm Kevin 2021-1-25
回答: Vishesh 2022-10-3
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)))

回答(1 个)

Vishesh
Vishesh 2022-10-3
  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

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

标签

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by