27 views (last 30 days)

Hello everyone,

i am using lsqcurvefit for fitting some data i have. The code i wrote is the following:

[x, resnorm, residual, exitflag, output] = lsqcurvefit(@(x,xdata)myfun(x,xdata,E_x,Gamma_X,Gamma_C), x0, xdata, ydata, lb, ub, options);

with given x0, E_x, Gamma_X, Gamma_C, lb and ub. The function myfun is in an another file called myfun.m. The fit works fine but I noticed that the result depends on the choice of the initial guess x0. So i tried to implement a multistart. The code i tried to write based on the examples on the help page is the following:

problem = createOptimProblem('lsqcurvefit','x0',x0,'objective',@myfun,'xdata',xdata,'ydata',ydata);

ms = MultiStart('PlotFcns',@gsplotbestf);

[xmulti,errormulti] = run(ms,problem,50)

This code does not work, it gives me the following error:

Error in myfun (line 9)

F(1,:) = real((E_c + E_x - j*(Gamma_X - Gamma_C))/2 + 1/2*sqrt((E_c - E_x - j*(Gamma_X - Gamma_C)).^2 + 4*par(2).^2));

Error in lsqcurvefit (line 202)

initVals.F = feval(funfcn_x_xdata{3},xCurrent,XDATA,varargin{:});

Error in fmultistart

Error in MultiStart/run (line 260)

fmultistart(problem,startPointSets,msoptions);

Error in CHO_matlab (line 91)

[xmulti,errormulti] = run(ms,problem,50)

Caused by:

Failure in initial objective function evaluation. LSQCURVEFIT cannot continue.

Failure in call to the local solver with supplied problem structure.

My understanding is that the function myfun within problem is missing the inputs parameters. Maybe there is also some other mistake which i do not know. So i replaced @myfun with @myfun(x,xdata,E_x,Gamma_X,Gamma_C) but now i get this error:

Unbalanced or unexpected parenthesis or bracket.

I also tried other similar combinations but noone seems to be acceptable.

What can i do it to make it work? How should i call the function with all the needed parameters?

Thank you all

Alan Weiss
on 9 Jul 2020

You almost had it right. Your objective function is

@(x,xdata)myfun(x,xdata,E_x,Gamma_X,Gamma_C)

where the arguments E_x,Gamma_X,Gamma_C must already be in your workspace when you call createOptimProblem.

Alan Weiss

MATLAB mathematical toolbox documentation

Walter Roberson
on 12 Jul 2020 at 23:14

Walter Roberson
on 13 Jul 2020 at 1:58

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.