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

1 view (last 30 days)
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.

Answers (1)

madhan ravi
madhan ravi on 10 Jul 2020
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 Comments
Rajdeep Mattu
Rajdeep Mattu on 10 Jul 2020
Edited: Rajdeep Mattu on 10 Jul 2020
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 on 10 Jul 2020
Edited: madhan ravi on 10 Jul 2020
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.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!