MATLAB: How to fit a complex valued function to the data

curvedatafitttingimaginaryOptimization Toolbox

I am trying to find parameters which would fit a complex valued function to my data, which is real. The function that I want to use is:
y = c*x*1i + x^2;

Best Answer

The Curve Fitting Toolbox does not accept complex valued functions. To carry out the fit, use the LSQNONLIN function or the FMINSEARCH function. The objective function passed to LSQNONLIN or FMINSEARCH should take the real and complex parts of the parameters separately and return the real and complex parts of the residuals separately.
For example, create the function 'myfun.m'.
function F = myfun(c,xdata,ydata)
% c is a two-element vector whose components are the real
% and imaginary parts of the parameter respectively
errors = (c(1) + c(2)*1i)*xdata*1i + xdata.^2 - ydata;
F = [real(errors(:)); imag(errors(:))];
Note that here, xdata and ydata may be complex, but the input and output are real.
To use this with LSQNONLIN:
[x,resnorm] = lsqnonlin(@(c)myfun(c,xdata,ydata),[1 3])
To use this with FMINSEARCH, add
F = sum(F.^2);
to the bottom of 'myfunc.m' and replace 'lsqnonlin' with 'fminsearch' in the above syntax.