How do I use a for loop for the newton raphson method?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
Alexander
2012년 10월 15일
In line 3 you overwrite your input parameter f with @x. What do you want to achieve with this?
답변 (1개)
arushi
2024년 8월 28일
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
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!