## 绘图函数

### 使用预定义的绘图函数

`type rosenbrockwithgrad`
```function [f,g] = rosenbrockwithgrad(x) % Calculate objective f f = 100*(x(2) - x(1)^2)^2 + (1-x(1))^2; if nargout > 1 % gradient required g = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1)); 200*(x(2)-x(1)^2)]; end ```

`type unitdisk2`
```function [c,ceq,gc,gceq] = unitdisk2(x) c = x(1)^2 + x(2)^2 - 1; ceq = [ ]; if nargout > 2 gc = [2*x(1);2*x(2)]; gceq = []; end ```

```options = optimoptions(@fmincon,Algorithm="interior-point",... SpecifyObjectiveGradient=true,SpecifyConstraintGradient=true,... PlotFcn={@optimplotx,@optimplotfval,@optimplotfirstorderopt});```

```x0 = [0,0]; A = []; b = []; Aeq = []; beq = []; lb = []; ub = [];```

```fun = @rosenbrockwithgrad; nonlcon = @unitdisk2; x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options)```

```Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance. ```
```x = 1×2 0.7864 0.6177 ```

### 创建自定义绘图函数

```function stop = plotfun(x,optimValues,state) stop = false; switch state case "init" % Set up plot case "iter" % Plot points case "done" % Clean up plots % Some solvers also use case "interrupt" end end ```

Global Optimization Toolbox 求解器使用不同语法。

```fun = @ras; rng(1) % For reproducibility x0 = 10*randn(2,1); % Random initial point opts = optimoptions(@fminunc,SpecifyObjectiveGradient=true,PlotFcn=@plotfandgrad); [x,fval] = fminunc(fun,x0,opts)```

```Local minimum found. Optimization completed because the size of the gradient is less than the value of the optimality tolerance. ```
```x = 2×1 1.9949 1.9949 ```
```fval = 17.9798 ```

```function stop = plotfandgrad(x,optimValues,state) persistent iters fvals grads % Retain these values throughout the optimization stop = false; switch state case "init" iters = []; fvals = []; grads = []; case "iter" iters = [iters optimValues.iteration]; fvals = [fvals optimValues.fval]; grads = [grads norm(optimValues.gradient)]; plot(iters,fvals,"o",iters,grads,"x"); legend("Objective","Norm(gradient)") case "done" end end```

```function [f,g] = ras(x) f = 20 + x(1)^2 + x(2)^2 - 10*cos(2*pi*x(1) + 2*pi*x(2)); if nargout > 1 g(2) = 2*x(2) + 20*pi*sin(2*pi*x(1) + 2*pi*x(2)); g(1) = 2*x(1) + 20*pi*sin(2*pi*x(1) + 2*pi*x(2)); end end```