1 | %% Optimization of a simple (Rosenbrock) function |
---|
2 | rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2; |
---|
3 | |
---|
4 | % With no constraints, operation simply passes through |
---|
5 | % directly to fminsearch. The solution should be [1 1] |
---|
6 | xsol = fminsearchcon(rosen,[3 3]) |
---|
7 | |
---|
8 | %% Only lower bound constraints |
---|
9 | xsol = fminsearchcon(rosen,[3 3],[2 2]) |
---|
10 | |
---|
11 | %% Only upper bound constraints |
---|
12 | xsol = fminsearchcon(rosen,[-5 -5],[],[0 0]) |
---|
13 | |
---|
14 | %% Dual constraints |
---|
15 | xsol = fminsearchcon(rosen,[2.5 2.5],[2 2],[3 3]) |
---|
16 | |
---|
17 | %% Mixed constraints |
---|
18 | xsol = fminsearchcon(rosen,[0 0],[2 -inf],[inf 3]) |
---|
19 | |
---|
20 | %% Fix a variable as constant, x(2) == 3 |
---|
21 | fminsearchcon(rosen,[3 3],[-inf 3],[inf,3]) |
---|
22 | |
---|
23 | %% Linear inequality, x(1) + x(2) <= 1 |
---|
24 | fminsearchcon(rosen,[0 0],[],[],[1 1],1) |
---|
25 | |
---|
26 | %% Nonlinear inequality, norm(x) <= 1 |
---|
27 | fminsearchcon(rosen,[0 0],[],[],[],[],@(x) norm(x) - 1) |
---|
28 | |
---|
29 | %% Minimize a linear objective, subject to a nonlinear constraints. |
---|
30 | fun = @(x) x*[-2;1]; |
---|
31 | nonlcon = @(x) [norm(x) - 1;sin(sum(x))]; |
---|
32 | fminsearchcon(fun,[0 0],[],[],[],[],nonlcon) |
---|
33 | |
---|
34 | %% Provide your own fminsearch options |
---|
35 | opts = optimset('fminsearch'); |
---|
36 | opts.Display = 'iter'; |
---|
37 | opts.TolX = 1.e-12; |
---|
38 | opts.MaxFunEvals = 100; |
---|
39 | |
---|
40 | n = [10,5]; |
---|
41 | H = randn(n); |
---|
42 | H=H'*H; |
---|
43 | Quadraticfun = @(x) x*H*x'; |
---|
44 | |
---|
45 | % Global minimizer is at [0 0 0 0 0]. |
---|
46 | % Set all lower bound constraints, all of which will |
---|
47 | % be active in this test. |
---|
48 | LB = [.5 .5 .5 .5 .5]; |
---|
49 | xsol = fminsearchcon(Quadraticfun,[1 2 3 4 5],LB,[],[],[],[],opts) |
---|
50 | |
---|
51 | %% Exactly fix one variable, constrain some others, and set a tolerance |
---|
52 | opts = optimset('fminsearch'); |
---|
53 | opts.TolFun = 1.e-12; |
---|
54 | |
---|
55 | LB = [-inf 2 1 -10]; |
---|
56 | UB = [ inf inf 1 inf]; |
---|
57 | xsol = fminsearchcon(@(x) norm(x),[1 3 1 1],LB,UB,[],[],[],opts) |
---|
58 | |
---|
59 | %% All the standard outputs from fminsearch are still returned |
---|
60 | [xsol,fval,exitflag,output] = fminsearchcon(@(x) norm(x),[1 3 1 1],LB,UB) |
---|
61 | |
---|