Newton Method Matlab code

조회 수: 24 (최근 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에서 Linear Algebra에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by