clear all
close all
eps=1.0;
p=ones(2,1); %Guess value for p
while eps>1.0e-14
[gfunc,jacobian]=ExampleFunctionWithJacobian(p);
eps=max(abs(gfunc));
temp=jacobian\(-gfunc); %this is more efficient than inv(jacobian)*(-gfunc)
p=temp+p;
end
options = optimoptions(@fsolve,’Display’,’iter’,’SpecifyObjectiveGradient’,true);
[pmatlab,F,exitflag,output,JAC] = fsolve(@ExampleFunctionWithJacobian,[1;1],options);
%Check to see if same as solution given by MATLAB fsolve()
abs(p-pmatlab)
function [gfunc,jac]=ExampleFunctionWithJacobian(p)
gfunc=[2*p(1)-2*p(2)-exp(-p(1)); -p(1)+2*p(2)-exp(-p(2))];
jac=[2+exp(-p(1)) -2;-1 2+exp(-p(2))];
end