# 基于问题的非线性最小二乘

### 模型

`$y\left(t\right)={A}_{1}\mathrm{exp}\left({r}_{1}t\right)+{A}_{2}\mathrm{exp}\left({r}_{2}t\right),$`

`$\sum _{t\in tdata}{\left(y\left(t\right)-ydata\right)}^{2}.$`

### 样本数据

```rng default % For reproducibility A = [1,2]; r = [-1,-3]; tdata = 3*rand(200,1); tdata = sort(tdata); % Increasing times for easier plotting noisedata = 0.05*randn(size(tdata)); % Artificial noise ydata = A(1)*exp(r(1)*tdata) + A(2)*exp(r(2)*tdata) + noisedata; plot(tdata,ydata,'r*') xlabel 't' ylabel 'Response'```

### 基于问题的方法

```A = optimvar('A',2); r = optimvar('r',2);```

```fun = A(1)*exp(r(1)*tdata) + A(2)*exp(r(2)*tdata); obj = sum((fun - ydata).^2);```

`lsqproblem = optimproblem("Objective",obj);`

```x0.A = [1/2,3/2]; x0.r = [-1/2,-3/2];```

`show(lsqproblem)`
``` OptimizationProblem : Solve for: A, r minimize : sum(arg6) where: arg5 = extraParams{3}; arg6 = (((A(1) .* exp((r(1) .* extraParams{1}))) + (A(2) .* exp((r(2) .* extraParams{2})))) - arg5).^2; extraParams{1}: 0.0139 0.0357 0.0462 0.0955 0.1033 0.1071 0.1291 0.1385 0.1490 0.1619 0.1793 0.2276 0.2279 0.2345 0.2434 0.2515 0.2533 0.2894 0.2914 0.2926 : : extraParams{2}: 0.0139 0.0357 0.0462 0.0955 0.1033 0.1071 0.1291 0.1385 0.1490 0.1619 0.1793 0.2276 0.2279 0.2345 0.2434 0.2515 0.2533 0.2894 0.2914 0.2926 : : extraParams{3}: 2.9278 2.7513 2.7272 2.4199 2.3172 2.3961 2.2522 2.1974 2.1666 2.0944 1.9566 1.7989 1.7984 1.7540 1.8318 1.6745 1.6874 1.5526 1.5229 1.5680 : : ```

### 基于问题的解

`[sol,fval] = solve(lsqproblem,x0)`
```Solving problem using lsqnonlin. Local minimum found. Optimization completed because the size of the gradient is less than the value of the optimality tolerance. ```
```sol = struct with fields: A: [2x1 double] r: [2x1 double] ```
```fval = 0.4724 ```

```figure responsedata = evaluate(fun,sol); plot(tdata,ydata,'r*',tdata,responsedata,'b-') legend('Original Data','Fitted Curve') xlabel 't' ylabel 'Response' title("Fitted Response")```

`disp(sol.A)`
``` 1.1615 1.8629 ```
`disp(sol.r)`
``` -1.0882 -3.2256 ```

`A` 中的拟合参数偏差约为 15%，`r` 中的拟合参数偏差约为 8%。

### 不受支持的函数要求 `fcn2optimexpr`

```fun = @(A,r) A(1)*exp(r(1)*tdata) + A(2)*exp(r(2)*tdata); response = fcn2optimexpr(fun,A,r); obj = sum((response - ydata).^2);```

`responsedata = evaluate(response,sol);`