Newton's method in Matlab

750 ビュー (過去 30 日間)
FURKAN CEVAHIR
FURKAN CEVAHIR 2019 年 1 月 26 日
コメント済み: Sergio E. Obando 2024 年 6 月 17 日
I am trying to apply Newton's method in Matlab, and I wrote a script:
syms f(x)
f(x) = x^2-4
g = diff(f)
x_1=1 %initial point
while f(['x_' num2str(i+1)])<0.001;% tolerance
for i=1:1000 %it should be stopped when tolerance is reached
['x_' num2str(i+1)]=['x_' num2str(i)]-f(['x_' num2str(i)])/g(['x_' num2str(i)])
end
end
I am getting this error:
Error: An array for multiple LHS assignment cannot contain M_STRING.
Newton's Method formula is x_(n+1)= x_n-f(x_n)/df(x_n) that goes until f(x_n) value gets closer to zero.
  1 件のコメント
John D'Errico
John D'Errico 2019 年 1 月 26 日
You should realize that things like this:
['x_' num2str(i+1)]=['x_' num2str(i)]-f(['x_' num2str(i)])/g(['x_' num2str(i)])
are not valid MATLAB syntax, that you cannot create or access variables on the fly like that.

サインインしてコメントする。

採用された回答

Basil C.
Basil C. 2019 年 1 月 26 日
編集済み: Basil C. 2019 年 1 月 26 日
You seem to have made some fudamentals errors in your code.
1. the variable 'x' cannot be used however you feel right
2. also with the for loop in your code would have to run for 1000 iteration every time which makes it inefficient so always put a condition inside it
Please use the below code....
syms f(x) x
f(x) = x^2-4;
g = diff(f);
x(1)=1 ;%initial point
for i=1:1000 %it should be stopped when tolerance is reached
x(i+1) = x(i) - f(x(i))/g(x(i));
if( abs(f(x(i+1)))<0.001) % tolerance
disp(double(x(i+1)));
break;
end
end
  3 件のコメント
Anurag Harsh
Anurag Harsh 2021 年 8 月 17 日
same here
Sergio E. Obando
Sergio E. Obando 2024 年 6 月 17 日
Basil's code works for me on R2024a. For an alternate solution that does not rely on symbolic variables, you can try this:
f = @(X) X.^2 - 4;
dfdx = @(X) 2*X;
nIter = 1000;
tol = 0.001;
x = zeros(1,nIter);
x(1) = 1;
for ii = 1:nIter
x(ii+1) = x(ii) - f(x(ii))/dfdx(x(ii));
if abs(f(x(ii+1))) < tol
disp(x(ii+1));
break
end
end
2.0000

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCalculus についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by