- 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)))".
- In your code, "c" is just a variable but you are trying to access it as an array.
- Below is the modified code where i am storing the "c" values (which is "x" values) in "x_values".
Newton Method Matlab code
10 ビュー (過去 30 日間)
古いコメントを表示
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)))
0 件のコメント
回答 (1 件)
Vishesh
2022 年 10 月 3 日
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
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!