newtraph.m
% Newton-Raphson root finding - single function
%
% The function and its derivative are defined in another script
% file as follows: (Note that this won't accept vector inputs)
%
% function [func, deriv] = fcn_nr(x)
% func = x^4 - 5*x^3 - 124*x^2 + 380*x + 1200;
% deriv = 4*x^3 - 15*x^2 - 248*x + 380;
% First, let's plot the function.
clear; clf; xp = -12:1:15; n = length(xp);
for i=1:n
yp(i) = fcn_nr(xp(i));
end
quickplt(xp,yp,'x','f(x)','Plot of function','grid')
hold on
% now proceed with finding a root:
x = input('Enter initial guess of root location: ');
itermax = 100; % max # of iterations
iter = 0;
errmax = 0.001; % convergence tolerance
error = 1;
fprintf('\n # root rel error\n\n');
while error > errmax & iter < itermax
iter = iter + 1;
[f fprime] = fcn_nr(x);
if fprime == 0
fprintf('ERROR: deriv(x) = 0; can''t divide by zero\n')
break;
end;
xnew = x - f / fprime; % here is new root estimate
error = abs((xnew - x)/xnew) * 100; % find change from previous
fprintf('%3i %10.6f %10.5f\n',iter,xnew,error);
x = xnew; % set up for next iteration
end
plot(x, fcn_nr(x),'ro')