Optimization
Optimization means finding the inputs that make something as small (or as large) as possible: the cheapest design, the best-fitting parameters, the shortest route. Roots & Minimization introduced fzero, fminbnd and fminsearch. This lesson looks at how to control those solvers, how to read what they report back, how to handle constraints with only the base functions, and what the Optimization Toolbox adds.
Which solver for which problem?
| Problem | Base MATLAB and Octave | Optimization Toolbox (MATLAB) |
|---|---|---|
| Root of f(x) = 0, one variable | fzero |
|
| Minimum of f(x) on [a, b] | fminbnd |
|
| Minimum of f(x), x a vector, no derivatives | fminsearch |
fminunc (Octave has fminunc in core) |
| Linear least squares with x ≥ 0 | lsqnonneg |
lsqlin |
| Nonlinear constraints | penalty tricks with fminsearch |
fmincon |
| Linear objective, linear constraints | linprog (Octave: glpk) |
|
| Integer variables | intlinprog |
All of these are local methods (except the linear programming ones, where every local minimum is global). They return the bottom of the valley they start in, so a good starting point matters.
Options and diagnostics
Every solver takes an options structure created with optimset. The most useful fields:
| Option | Meaning | fminsearch default |
|---|---|---|
TolX |
Stop when steps in x become smaller than this | 1e-4 |
TolFun |
Stop when changes in f become smaller than this | 1e-4 |
MaxIter |
Maximum iterations | 200 * numel(x0) |
MaxFunEvals |
Maximum function evaluations | 200 * numel(x0) |
Display |
'off', 'final', 'iter' (prints a progress table) |
'notify' |
The defaults are loose: four digits at best. Tighten them when you need more, and always ask for the extra outputs exitflag (1 means converged; 0 means it hit an iteration limit) and output (a struct with counts and a message):
% Where should a warehouse go to minimise the total distance to four shops?
shops = [0 0; 10 0; 10 8; 2 9];
total = @(p) sum(sqrt(sum((shops - p).^2, 2)));
opts = optimset('TolX', 1e-10, 'TolFun', 1e-10, 'MaxIter', 5000, 'MaxFunEvals', 5000);
[p, dist, exitflag, output] = fminsearch(total, mean(shops), opts);
fprintf('best location: (%.4f, %.4f), total distance %.4f\n', p, dist);
fprintf('exitflag = %d, output has an iterations field: %d\n', exitflag, isfield(output, 'iterations'));
fprintf('centre of mass gives %.4f\n', total(mean(shops)));best location: (5.8442, 4.6753), total distance 24.8478
exitflag = 1, output has an iterations field: 1
centre of mass gives 24.8983
The best point (the geometric median) is not the average of the shop positions, and there's no formula for it: a typical job for a derivative-free solver. shops - p relies on implicit expansion, which both MATLAB (R2016b+) and Octave support. The exact iteration count differs between MATLAB and Octave, which is why it isn't printed.
Tip:
optimset('Display', 'iter')shows the solver's progress line by line. It's the first thing to try when a solver returns something unexpected.
One variable on an interval: fminbnd
fminbnd combines golden-section search with parabolic interpolation and needs only an interval, no starting point. A classic design question: what radius minimises the metal needed for a 1-litre cylindrical can?
V = 1000; % volume in cm^3
areaOf = @(r) 2*pi*r.^2 + 2*V ./ r; % top + bottom + side (h = V/(pi r^2))
[r, A, exitflag] = fminbnd(areaOf, 1, 20);
h = V / (pi * r^2);
fprintf('radius %.4f cm, height %.4f cm, area %.2f cm^2 (exitflag %d)\n', r, h, A, exitflag);
fprintf('calculus says r = (V/(2*pi))^(1/3) = %.4f, so h = 2r\n', (V / (2*pi))^(1/3));radius 5.4193 cm, height 10.8385 cm, area 553.58 cm^2 (exitflag 1)
calculus says r = (V/(2*pi))^(1/3) = 5.4193, so h = 2r
Constraints without a toolbox
Base MATLAB has no general constrained solver, but two tricks cover many practical cases.
Penalty functions
Add a term that is zero when the constraint holds and grows quickly when it's violated, then minimise the sum with fminsearch. A larger penalty weight mu pushes the solution closer to feasibility. Here we minimise the distance to (3, 2) subject to x + y ≤ 4; the exact answer is (2.5, 1.5):
f = @(v) (v(1) - 3)^2 + (v(2) - 2)^2;
g = @(v) v(1) + v(2) - 4; % constraint g(v) <= 0
opts = optimset('TolX', 1e-10, 'TolFun', 1e-10, 'MaxIter', 5000, 'MaxFunEvals', 5000);
v = [0 0];
for mu = [1 10 100 1e4]
penalised = @(v) f(v) + mu * max(0, g(v))^2;
v = fminsearch(penalised, v, opts); % warm start from the previous answer
fprintf('mu = %-6g x = %.4f, y = %.4f, violation %.1e\n', mu, v, max(0, g(v)));
endmu = 1 x = 2.6667, y = 1.6667, violation 3.3e-01
mu = 10 x = 2.5238, y = 1.5238, violation 4.8e-02
mu = 100 x = 2.5025, y = 1.5025, violation 5.0e-03
mu = 10000 x = 2.5000, y = 1.5000, violation 5.0e-05
The violation shrinks roughly like 1/mu. Very large weights make the problem badly scaled, so increase mu gradually and reuse each answer as the next start, as above.
Change of variables
Simple bounds can be removed by reparametrising. To keep x > 0, optimise over z and use x = exp(z); to keep a ≤ x ≤ b, use x = a + (b − a)·(sin(z) + 1)/2. The solver then works without constraints:
% fit y = A*exp(-k t) with A > 0 and k > 0 guaranteed
t = 0:5;
y = [8.1 4.9 3.0 1.8 1.1 0.7];
model = @(z, t) exp(z(1)) * exp(-exp(z(2)) * t);
sse = @(z) sum((model(z, t) - y).^2);
opts = optimset('TolX', 1e-10, 'TolFun', 1e-12, 'MaxIter', 5000, 'MaxFunEvals', 5000);
z = fminsearch(sse, [0 0], opts);
fprintf('A = %.4f, k = %.4f (both positive by construction)\n', exp(z(1)), exp(z(2)));A = 8.0931, k = 0.4983 (both positive by construction)
Nonnegative least squares: lsqnonneg
Least-squares problems often have physical quantities that can't be negative: amounts of ingredients, concentrations, intensities. Plain backslash ignores that; lsqnonneg(C, d) finds the best x with all x ≥ 0:
% Mix three feeds (columns) to match a nutrient target (rows) as closely as possible
C = [8 2 1; 3 7 2; 1 3 9; 5 5 5];
d = [10; 4; 6; 8];
xFree = C \ d;
xPos = lsqnonneg(C, d);
fprintf('backslash: %s, residual %.4f\n', mat2str(round(xFree' * 1e4) / 1e4), norm(C * xFree - d));
fprintf('lsqnonneg: %s, residual %.4f\n', mat2str(round(xPos' * 1e4) / 1e4), norm(C * xPos - d));backslash: [1.1972 -0.1152 0.5619], residual 0.2703
lsqnonneg: [1.1447 0 0.514], residual 0.6783
The unconstrained answer asks for a negative amount of feed 2, which is impossible. lsqnonneg sets it to zero and re-balances the others; the residual is a little larger, the price of a realistic answer.
The Optimization Toolbox
MATLAB's Optimization Toolbox adds solvers for constrained and structured problems. They are not part of base MATLAB, and Octave doesn't provide them under these names (its core has sqp, qp and glpk instead), so the examples below are MATLAB-only and not runnable here.
fmincon handles bounds, linear and nonlinear constraints. The penalty problem from above:
f = @(v) (v(1) - 3)^2 + (v(2) - 2)^2;
Aineq = [1 1]; bineq = 4; % x + y <= 4
opts = optimoptions('fmincon', 'Display', 'final');
v = fmincon(f, [0 0], Aineq, bineq, [], [], [], [], [], opts)MATLAB output:
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.
v =
2.5000 1.5000linprog solves linear programs. A workshop makes tables (profit 3) and chairs (profit 5) with limits x ≤ 4, 2y ≤ 12 and 3x + 2y ≤ 18. linprog minimises, so maximise profit by minimising its negative:
f = -[3; 5];
A = [1 0; 0 2; 3 2];
b = [4; 12; 18];
lb = [0; 0];
[x, fval] = linprog(f, A, b, [], [], lb)MATLAB output:
Optimal solution found.
x =
2
6
fval =
-36intlinprog adds integer variables (here: which of four projects to fund within a budget of 10):
value = [9 7 6 4]; cost = [6 4 3 2];
x = intlinprog(-value, 1:4, cost, 10, [], [], zeros(4,1), ones(4,1))MATLAB output (after the solver's progress messages):
x =
0
1
1
1Small problems like these can be cross-checked with plain code. The optimum of a linear program sits at a corner of the feasible region, and a 0/1 problem with four variables has only 16 candidates:
% LP: check every intersection of two constraint lines
A = [1 0; 0 2; 3 2; -1 0; 0 -1]; % includes x >= 0, y >= 0
b = [4; 12; 18; 0; 0];
best = -Inf;
for i = 1:size(A, 1)
for j = i+1:size(A, 1)
M = A([i j], :);
if abs(det(M)) > 1e-12
v = M \ b([i j]);
if all(A * v <= b + 1e-9) && 3*v(1) + 5*v(2) > best
best = 3*v(1) + 5*v(2);
vBest = v;
end
end
end
end
fprintf('LP optimum: x = %g, y = %g, profit %g\n', vBest, best);
% 0/1 knapsack: try all 2^4 choices
value = [9 7 6 4]; cost = [6 4 3 2];
choices = dec2bin(0:15) - '0'; % 16 x 4 matrix of 0/1 rows
ok = choices * cost' <= 10;
total = choices * value';
total(~ok) = -Inf;
[bestValue, k] = max(total);
fprintf('knapsack: fund %s, value %d\n', mat2str(choices(k, :)), bestValue);LP optimum: x = 2, y = 6, profit 36
knapsack: fund [0 1 1 1], value 17
Enumeration explodes for real sizes, of course; that's what the toolbox solvers (or Octave's glpk) are for.
Learn more: the same solvers in Python are in SciPy optimizers, constrained optimization and linear programming; fitting models is continued in Curve Fitting.
Test yourself
fminsearch returns exitflag = 0. What does that mean?
- It found the global minimum
- It stopped at the iteration or function-evaluation limit before converging
- The function is not differentiable
- The minimum value is 0
How can you keep a parameter k strictly positive when fitting with fminsearch?
- Set the option 'Positive'
- Optimise z and use k = exp(z) inside the model
- Use abs(fminsearch(...))
- It is impossible without a toolbox
Which base function finds the least-squares solution with all components ≥ 0?
lsqnonneglinprogfminbndpinv