Plotting approximation error in Newton-Raphson

Hello all,
In a script I'm trying to find roots of a function by Newton-Raphson method. In each iteration I'm finding and printing the relative approximation error.
What I want is, instead of printing them I would like plot my function and my relative approximation error in each iteration.
Any help is much appreciated.
My script file:
function [r] = newton(x1)
n = 1000;
tol_error = 0.001;
r = x1;
for t=1:n
x_plus = x1 - (my_func(x1)/my_func_diff(x1));
approx_error(t) = abs((x_plus - x1)/(x_plus))*100;
if (approx_error(t) < tol_error)
display(t);
display(approx_error(t));
r = x_plus;
return;
else
x1 = x_plus;
end
end
end
function y = my_func_diff(x)
y = 3*(x^2) - 20*x - 43;
end
function y = my_func(x)
y = x^3 - 10*(x^2) - 43*x + 52;
end

 Accepted Answer

Hidir, I assume you are using a while-loop that you execute until the relative error is smaller than some given tolerance. Something like:
ii = 0; % define a loop index (= iteration number)
while (abs(err) > tol)
ii = ii + 1; % increment loop index
... % do some computations
err(ii) = ... % compute and save relative error as vector
end
plot(ii,err,'rs',ii,fun) % plot error along with function value

3 Comments

Doesn't seem to be working mate. I included my code, it might help you.
Here you go:
function [r] = newton(x1)
n = 1000;
tol_error = 0.00001;
r = x1;
for t=1:n
x_plus = x1 - (my_func(x1)/my_func_diff(x1));
approx_error(t) = abs((x_plus - x1)/(x_plus))*100;
fun_val(t) = my_func(x1); % save function values as vector
if (approx_error(t) < tol_error)
display(t);
display(approx_error(t));
r = x_plus;
break; % use break instead of return
else
x1 = x_plus;
end
end
plot(1:t,approx_error,'rs-',1:t,fun_val,'bd-')
grid
end
Works like a charm. Ty !

Sign in to comment.

More Answers (0)

Categories

Find more on App Building in Help Center and File Exchange

Tags

Asked:

on 15 Mar 2014

Commented:

on 19 Mar 2014

Community Treasure Hunt

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

Start Hunting!