How do I use a for loop for the newton raphson method?

3 visualizaciones (últimos 30 días)
yo
yo el 14 de Oct. de 2012
Respondida: arushi el 28 de Ag. de 2024
The code I have is where f is a function handle, a is a real number, and n is a positive integer:
function r=mynewton(f,a,n)
syms x
f=@x;
c=f(x);
y(1)=a;
for i=[1:length(n)]
y(i+1)=y(i)-(c(i)/diff(c(i)));
end;
r=y
The erros I am getting are:
Undefined function or variable 'x'.
Error in mynewton (line 4)
c=f(x);
How do I fix these errors?
  1 comentario
Alexander
Alexander el 15 de Oct. de 2012
In line 3 you overwrite your input parameter f with @x. What do you want to achieve with this?

Iniciar sesión para comentar.

Respuestas (1)

arushi
arushi el 28 de Ag. de 2024
Hi Yo,
Here's the corrected version of your Newton's method implementation:
function r = mynewton(f, a, n)
syms x
% Symbolically define the function
c = f(x);
% Calculate the derivative of the function
dc = diff(c);
% Initialize the first guess
y(1) = a;
% Perform Newton's iteration
for i = 1:n
% Evaluate the function and its derivative at the current guess
f_val = subs(c, x, y(i));
df_val = subs(dc, x, y(i));
% Update the guess using Newton's formula
y(i+1) = y(i) - double(f_val) / double(df_val);
end
% Return all iterations
r = y;
end
Hope this helps.

Community Treasure Hunt

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

Start Hunting!

Translated by