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

13 ビュー (過去 30 日間)
yo
yo 2012 年 10 月 14 日
回答済み: arushi 2024 年 8 月 28 日
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
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
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.

カテゴリ

Help Center および File ExchangeNewton-Raphson Method についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by