How to save each guess / output as an array via Newton's Method?

2 ビュー (過去 30 日間)
Rajdeep Mattu
Rajdeep Mattu 2020 年 7 月 10 日
編集済み: madhan ravi 2020 年 7 月 10 日
Currently doing the Newton's Method for a homework problem.
Here's how the lecture demonstrated this.
x = 3; % Our initial Guess.
f = @(x) x.^2 - 191; % Our equation.
f_prime = @(x) 2*x; % Deriviative of Equation.
tol = 1e-4 % Our Tolerance.
for i = 1:1000 % Let this sucker go up to 1000.
x = x - f(x)/f_prime(x);
if abs(f(x)) < tol
break
end
end
if i == 1000
warning('Newtons''s method did not converge.');
end
approx_root = x; % Root done by computation above.
true_root = sqrt(191); % Actual Root.
disp(abs(true_root - approx_root)); % This is the error.
disp(i) % This is the number of iterations it took.
Now, I don't know how to store each guess into a row vector.
If I wanted to store each guess into a row vector? How would you go about that? I'm certain there's a for loop component to it.

回答 (1 件)

madhan ravi
madhan ravi 2020 年 7 月 10 日
x = zeros(1e3, 1);
x(1) = 3;
for ii = 2:1e3 % Let this sucker go up to 1000.
x(ii) = x(ii-1) - f(x(ii-1))/f_prime(x(ii-1));
if abs(f(x(ii-1))) < tol
break
end
end
  2 件のコメント
Rajdeep Mattu
Rajdeep Mattu 2020 年 7 月 10 日
編集済み: Rajdeep Mattu 2020 年 7 月 10 日
Can you explain this more in english on what's going on?
And this wouldn't be inside the original for loop right? But outside of it?
madhan ravi
madhan ravi 2020 年 7 月 10 日
編集済み: madhan ravi 2020 年 7 月 10 日
f = @(x) x.^2 - 191; % Our equation.
f_prime = @(x) 2*x; % Deriviative of Equation.
tol = 1e-4 % Our Tolerance.
x = zeros(1e3, 1);
x(1) = 3; % Our initial Guess.
for ii = 2:1e3 % Let this sucker go up to 1000.
x(ii) = x(ii-1) - f(x(ii-1))/f_prime(x(ii-1));
if abs(f(x(ii-1))) < tol
break
end
end
if ii == 1000
warning('Newtons''s method did not converge.');
end
approx_root = x; % Root done by computation above.
true_root = sqrt(191); % Actual Root.
disp(abs(true_root - approx_root)); % This is the error.
disp(ii) % This is the number of iterations it took.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by