# 对复数值数据进行模型拟合

### 含噪人工数据

rng default % for reproducibility N = 100; % number of observations v0 = [2;3+4i;-.5+.4i]; % coefficient vector xdata = -log(rand(N,1)); % exponentially distributed noisedata = randn(N,1).*exp((1i*randn(N,1))); % complex noise cplxydata = v0(1) + v0(2).*exp(v0(3)*xdata) + noisedata; 

### 拟合模型以恢复系数向量

objfcn = @(v)v(1)+v(2)*exp(v(3)*xdata) - cplxydata; 

opts = optimoptions(@lsqnonlin,'Display','off'); x0 = (1+1i)*[1;1;1]; % arbitrary initial guess [vestimated,resnorm,residuals,exitflag,output] = lsqnonlin(objfcn,x0,[],[],opts); vestimated,resnorm,exitflag,output.firstorderopt 
vestimated = 2.1582 + 0.1351i 2.7399 + 3.8012i -0.5338 + 0.4660i resnorm = 100.9933 exitflag = 3 ans = 0.0018 

lsqnonlin 将复系数向量恢复为一个有效数字。残差范数相当大，表明噪声使模型无法拟合所有观测值。退出标志是 3 而不是首选的 1，因为一阶最优性测度大约是 1e-3，未低于 1e-6

### 替代方法：使用 lsqcurvefit

objfcn = @(v,xdata)v(1)+v(2)*exp(v(3)*xdata); 

opts = optimoptions(@lsqcurvefit,opts); % reuse the options [vestimated,resnorm] = lsqcurvefit(objfcn,x0,xdata,cplxydata,[],[],opts) 
vestimated = 2.1582 + 0.1351i 2.7399 + 3.8012i -0.5338 + 0.4660i resnorm = 100.9933 

### 替代方法：拆分实部和虚部

function yout = cplxreal(v,xdata) yout = zeros(length(xdata),2); % allocate yout expcoef = exp(v(5)*xdata(:)); % magnitude coscoef = cos(v(6)*xdata(:)); % real cosine term sincoef = sin(v(6)*xdata(:)); % imaginary sin term yout(:,1) = v(1) + expcoef.*(v(3)*coscoef - v(4)*sincoef); yout(:,2) = v(2) + expcoef.*(v(4)*coscoef + v(3)*sincoef); 

ydata2 = [real(cplxydata),imag(cplxydata)]; 

x0 = ones(6,1); [vestimated,resnorm,residuals,exitflag,output] = ... lsqcurvefit(@cplxreal,x0,xdata,ydata2); vestimated,resnorm,exitflag,output.firstorderopt 
Local minimum possible. lsqcurvefit stopped because the final change in the sum of squares relative to its initial value is less than the value of the function tolerance. vestimated = 2.1582 0.1351 2.7399 3.8012 -0.5338 0.4660 resnorm = 100.9933 exitflag = 3 ans = 0.0018