clear all
close all
%% Defining functions:
%defining functions f_1 and f_2,
f1=(@(x,y) (x.^2-2*x-y+0.5));
f2=(@(x,y) (x.^2+4*y.^2-4));
f=(@(v) [(v(1).^2-2*v(1)-v(2)+0.5);(v(1).^2+4*v(2).^2-4)]);%vectorised version
%Defining a function to calculate the Jacobian matrix of partial
%derivatives.

J=(@(v) [2*v(1)-2,-1;2*v(1),8*v(2)] );

%% Plotting
figure
fimplicit(f1,[-2.5 2.5 -1 1.5],'LineWidth',2)
hold on
fimplicit(f2,[-2.5 2.5 -1 1.5],':r','LineWidth',2)
xlabel('$x$','interpreter','latex','FontSize', 18)
ylabel('$y$','interpreter','latex','FontSize', 18)

%% 
v1=[1.75;0.25];%initial guess for root1
v2=[-0.25;1];%inititial guess for root2
plot([v1(1),v2(1)],[v1(2),v2(2)],'og')% Show guess on graph



%% calculating rootes using function at end of file 
% prints roots to comand window
root1=newtonMV(f, J,v1)
root2=newtonMV(f, J,v2)
% Show roots on graph
plot([root1(1),root2(1)],[root1(2),root2(2)],'ok','LineWidth',2,'MarkerFaceColor','r')

print( '-depsc2', 'Q2fig' )%save figure for report

%% Newton's method solution for root 1
% Newton method for finding roots of functions of a multiple variable.
% F is a vector function
% Fprime is the Jacobian matrix of partial derivitives

function root=newtonMV(F, Fprime,guess)
iter=1;
maxiter=1000;
v=guess;
accuracy=1;
tolerance=1e-12;
while accuracy>tolerance && iter<maxiter;
    v=v-feval(Fprime,v)\feval(F,v);
    accuracy=norm(feval(F,v));
end
root=v;
end
