How do I use a for loop for the newton raphson method?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Alexander
am 15 Okt. 2012
In line 3 you overwrite your input parameter f with @x. What do you want to achieve with this?
Antworten (1)
arushi
am 28 Aug. 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.
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!