MATLAB: Function handle not updating between multiple fsolve calls

fsolvefunction handlejacobian

Hello, I am trying to solve a series of different system of equations with fsolve. The system of equations and its size can change dynamically between each solve. So right now, I do this by updating the function/jacobian file between each solve before passing their function handles to fsolve.
However after the first solve, I encounter the error "Error using ==> fsolve at 298 User-defined Jacobian is not the correct size…"
But when I check the jacobian file, it does have have the correct size. This leads me to think somehow the function handle is not getting "refresh" between the fsolve calls?
I can reproduce the problem on R2009b with the following example:
options = optimset('Jacobian','on');
% first solve
fid = fopen('foo.m','W');
fprintf(fid,'function [F,J]=foo(x)\n');
fprintf(fid,'F(1)=x(1)^3;\n');
fprintf(fid,'J(1,1)=3*x(1)^2;\n');
fprintf(fid,'end');
fclose(fid);
[F,V] = fsolve(@foo,zeros(1,1),options);
% second solve with a different system
fid = fopen('foo.m','W');
fprintf(fid,'function [F,J]=foo(x)\n');
fprintf(fid,'F(1)=x(1)^2;\n');
fprintf(fid,'J(1,1)=2*x(1);\n');
fprintf(fid,'F(2)=x(2);\n');
fprintf(fid,'J(2,2)=1;\n');
fprintf(fid,'end');
fclose(fid);
[F,V] = fsolve(@foo,zeros(2,1),options);
Any suggestion/comment is much appreciated. Thanks.

Best Answer

After you change the file,
clear foo