MATLAB: Using lsqnonlin () for solution of an nonlinear equation

lsqnonlinnonlinearoptimization

Please consider the following code:
function diff = myfun(D,Y)
t = 0:30:600;
l = length(t);
a = 0.5*0.75*10^(-4);
for i = 1:l
Yp(i)=0;
for n = 1:10
y(i,n) = exp(-D*t(i)*(pi^2)*(n^2)/(a^2))/n^2;
Yp(i) = Yp(i) + y(i,n);
end
end
diff = 1- (6*Yp/pi^2)-Y;
%function
Y = [0.0566 0.4432 0.5539 0.6783 0.7303 0.3569 0.4001 0.4278 0.4499 0.4720 ...
0.4500 0.5157 0.5237 0.5492 0.5590 0.5799 0.5890 0.6000 0.6150 0.6300...
0.6450];
D0 = 2.0*10^(-12);
options=optimset('LargeScale','on','Display','iter','MaxFunEvals',1e20,'TolFun',2e-50,'TolX',2e-50,'LevenbergMarquardt','on');
[D,resnorm,residual,exitflag,output,lambda]=lsqnonlin(@myfun,D0,[],[],options);
I am trying to get D value using the lsqnonlin() but I am getting the message:
Error using ==> feval
Undefined function or method 'diffusion' for input arguments of type 'double'.
Error in ==> lsqnonlin at 200
initVals.F = feval(funfcn{3},xCurrent,varargin{:});
Caused by:
Failure in initial user-supplied objective function evaluation. LSQNONLIN cannot continue.
Please help me with the code why I am getting this error message. What could be the better possible way to obtain the solution for D value.

Best Answer

I suspect that the code you are running is not the code you have shown. The posted myfun(D,Y) takes 2 arguments, but you are not passing a value for Y to myfun in any way. MATLAB should be complaining that Y is missing, unless your call to lsqnonlin looks something like this,
[D,resnorm,residual,exitflag,output,lambda]=lsqnonlin(@(D) myfun(D,Y), D0,[],[],options);
Also, if D is a scalar, it would be probably be much simpler to use fminsearch instead of lsqnonlin to minimize norm(diff).