% 6.581 PS4
% Problem 1
% newton.m

function [x, e, flag] = newton(func, x0, tol, maxItr)

% Implements Newton's method. The arguments to this function are as
% follows:
%
% func - is a vector function of x. The return value of func is the time
% derivative of x evaluated at x and the jacobian evaluated at x.
% For example:
% function [dxdt, dxdx] = myfun(x)
% dxdt = -x^2;
% dxdx = -2*x;
% x0 - is the initial guess
% tol - the error tolerance. When the two norm of func(x) is below tol
% the function will return
% maxItr - the maximum number of steps before the method gives up. If this
% happens then the error flag will be set to 0;
%
% Returns:
%
% x - If successfull this is the the root of the function
% e - The residual error. This is the two norm of func(x)
% flag - 1 if the method met the error tolerance. 0 otherwise.
%
% You will have to fill in the missing lines of code labled with
% %% CHANGE ME

i = 1
x = x0

[f, fp] = func(x)
e = norm(f)

while(e > tol && i < maxItr)
dx = ; %% CHANGE ME %%
x = x + dx;
[f, fp] = func(x);
e = norm(f);
i = i + 1
end;

if(e > tol)
flag = 0;
else
flag = 1;
end