

%nonlinear solvers lab 3

%simple exampels

x=fzero(@sin,x0=[3.1,3.2])
x-pi

[x,fx,info,output]=fzero(@sin,x0=[3.1,3.2])

%changing options e.g .TolX
x=fzero(@sin,x0=[3.1,3.2],optimset("tolX",1e-2))
x-pi %lower precision

%counting no of calls

function [y,dy]=f(x)
  y=x*x-2;
  if(nargout==2)
   dy=2*x;
  end 
end
 
x(1)=fzero(@f,[1,2]);
[x(2),~,~,output2]=fsolve(@f,2);
[x(3),~,~,output3]=fsolve(@f,2,optimset("Jacobian","on"));
x-sqrt(2)
output2
output3
%2D case
disp("x(1)^2+x(2)^2-1=0; x(!)+x(2)=0");
function [y,dy]=f(x)
  y=[x'*x-1;[1,1]*x];
  if(nargout==2)
   dy=[2*x';[1,1]];
  end 
end
%to test f(x)
x0=[1;2];
y=f(x0)
[y,dy]=f(x0)

[x1,~,~,output1]=fsolve(@f,x0);
[x2,~,~,output2]=fsolve(@f,x0,optimset("Jacobian","on"));
x1
x2
output1
output2


%implicit function
%compute a graph of f:[x0,x0+L]-->R defined implicitely
%F(x,f(x))=0 for given F:D \subset R^2 --> R^2
%knowing F(x0,y0)=0 i.e. f(x0)=y0
%take F(x,y)=x^2+y^2-1 i.e. a circle equation
function z=F(x,y)
  z=x.*x+y.*y-1;
end

b=1-eps;  
N=300;
x=linspace(0,b,N);
y=zeros(size(x));  
y(1)=1.0;
Fcount=0;
for k=2:N,
%y0 = y(k-1) the solution for neigboring equation
% [y(k),~,info,output]=fsolve(@(y) F(x(k),y),y(k-1));  
%x0=1
% [y(k),~,info,output]=fsolve(@(y) F(x(k),y),1);
%using fzero
%y0 = y(k-1) the solution for neigboring equation
 [y(k),~,info,output]=fzero(@(y) F(x(k),y),[y(k-1),0]);  
%x0=[0,1]
% [y(k),~,info,output]=fzero(@(y) F(x(k),y),[0,1]);
 
 Fcount+=output.funcCount;
 if(info!=1)
  disp("Something wrong\n");
  break;
 end 
end
Fcount

plot(x,y,";y=f(x):x^2+y^2-1=0;");
pause(2);
plot(x,F(x,y),";z=x^2+y^2-1;")

%same for another F
function z=F(x,y)
  z=x.*x.*x+y.*y.*y-y;
end
b=0.6;  
N=300;
x=linspace(0,b,N);
y=zeros(size(x));  
y(1)=0.0;

for k=2:N,
%y0 = y(k-1) the solution for neigboring equation
 [y(k),~,info,output]=fsolve(@(y) F(x(k),y),y(k-1));  
%x0=1
% [y(k),~,info,output]=fsolve(@(y) F(x(k),y),1);
 
 if(info!=1)
  disp("Something wrong\n");
  break;
 end 
end


plot(x,y,";y=f(x): x^3+y^3-y=0;");
pause(1);
plot(x,F(x,y),";z=x^3+y^3-y;")
