Optimization Techniques in MATLAB
Optimization Techniques in MATLAB
Optimization Techniques in MATLAB
es
Table of Contents
MLOP1222V1
TOC - 1
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Table of Contents
This Training Course Notebook, along with other Training Course Examples
and Exercises, shall at all times remain the intellectual property of The
MathWorks, Inc. The MathWorks, Inc. reserves all rights in these materials.
No part of these materials may be photocopied, reproduced in any form, or
distributed without prior written consent from The MathWorks, Inc.
Table of Contents
1. Introduction
2. Running an Optimization Problem
3. Specifying Objective Functions and Constraints
4. Solvers and Performance
5. Global and Multiobjective Optimization
6. Conclusion
Appendices
Introduction
MathWorks® at a Glance������������������������������������������������������������������������1 - 2
MathWorks® Product Overview ����������������������������������������������������������1 - 3
Computer Setup��������������������������������������������������������������������������������������1 - 4
What Can You Do with MATLAB®, Optimization Toolbox™, and
Global Optimization Toolbox™?������������������������������������������������������1 - 5
Course Learning Outcomes������������������������������������������������������������������1 - 6
Course Outline����������������������������������������������������������������������������������������1 - 7
Conclusion
Course Outline����������������������������������������������������������������������������������������6- 2
Further Training and Certification������������������������������������������������������6- 3
MathWorks® Web Resources����������������������������������������������������������������6- 4
Technical Support����������������������������������������������������������������������������������6- 5
Course Evaluation����������������������������������������������������������������������������������6- 6
Appendices
Exercises������������������������������������������������������������������������������������������������������ A
Extra Examples �������������������������������������������������������������������������������������������B
Introduction
1 - 1
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Introduction
MathWorks® at a Glance
MathWorks® is the leading developer of mathematical computing
software in the world.
• Privately held
• Over 4000 employees worldwide
• More than 2 million users in 180+ countries
MathWorks supports programs that inspire learning and advance education Worldwide Offices
in engineering, science, and math.
For information on any of our worldwide offices, please open the following
• 5000+ universities around the world location on the MathWorks site and choose a country:
• 1800+ MATLAB® and Simulink® based books
www.mathworks.com/company/worldwide/
Control Systems
Event-Based Modeling Physical Modeling
SIMULINK
Simulation and Model-Based Design
®
MATLAB
The Language of Technical Computing
®
Computational Finance
fmincon
Course Outline
Day 1
• Introduction
• Running an Optimization Problem
• Specifying the Objective Functions and Constraints
• Solvers and Performance
• Global and Multiobjective Optimization
• Conclusion
In order to maintain consistency with instructors presentation and enable users to follow along with greater ease,
blank pages have been inserted throughout this course manual.
Running an
Optimization
Problem
2 - 1
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Running an Optimization Problem
Outline
• Optimization task
• Components of a problem
• The optimization process
hopt = 7.26
ropt = 3.63
Open a Live Script and add an Optimization task. Select the recommended
Optimization Toolbox provides a task interface that allows you to define and
Problem-based approach.
run optimization problems interactively.
First, open a Live Script by clicking the New Live Script button under
the HOME tab. Then, click the Task button under the INSERT tab of the
MATLAB® toolstrip.
The Task button opens a dropdown menu. Scroll down and click the
Optimize button. This loads the task into the Live Script.
Two options are presented in the Task: the Problem-based approach and
the Solver-based approach. In this course, the problem-based approach is
chosen in most cases. Exceptions to this will be noted.
For the soup can problem, you can specify the details of the problem by
selecting the appropriate options in each field.
In the Live Task, under the Create optimization variables section, create
The design variables or optimization variables of a problem are the parameters
a continuous 1-by-1 optimization variable named radius with a lower
than can be changed to achieve the optimization goal. Performing an
bound of zero and an initial point of 5 cm.
optimization entails finding the “best” values of the design variables.
Click the plus button to the right of optimization variable to add another
In the optimization task, you can create the optimization or design variables optimization variable. Name this variable named height with a lower
under the Create optimization variables section. Here you can specify the bound of zero, an upper bound of 15 cm and an initial point of 8 cm. Keep
name of the variable, the dimensions, the type, bounds and initial point it a continuous 1-by-1 variable.
guess.
In the soup can example, the design variables are the height and radius of
the can. Both of these can be treated as 1-by-1 scalar variables that can take
on continuous values. Note that you can also treat them as the elements of a
2-by-1 or 1-by-2 vector.
In the Live Task, under the Define problem section, select the Minimize
The goal of performing an optimization is to minimize or maximize the
button for the Goal. For the Objective, select the Define on one line option
objective function. The objective function takes the design variables as input,
in the dropdown menu. In the text box, write the objective function in
and returns a single performance measure as output.
terms of the can radius and height:
In the soup can example, the objective function is the cost of the construction 2*pi*radius*(radius+height)
materials. Since the cost is assumed to be proportional to the surface area, the
objective function is effectively the surface area of a cylinder, as a function of
its radius and height (the design variables).
In the Problem-based Live Task, the objective function can be defined under
the Define problem section. For the Goal, select a button to minimize or
maximize the objective function. For the Objective, use the dropdown
menu to specify where the function is defined. You can define it on one line,
or use a local function or function file.
Add the constraint to the problem to limit the height of the can to be below
Constraints are restrictions on the possible values of the design variables.
four times the radius to prevent the can from tipping over easily. Define
These can be simple limits, such as the height of the can being no greater
the expression on one line such that the left-hand side is less-than-or-equal
than 15 cm. They can be relationships between the variables, such as the
to the right-hand side.
height being no more than four times the radius, and the can having a fixed
volume: height <= 4*radius
V (r, y) = πr2 h = 300 Click the plus sign next to the constraint to add another constraint.
Here you will add the liquid volume constraint. In the dropdown menu,
In the Live Task, under the Define problem section, constraints can be
select Function file, click the Browse to file button and select the
specified and added to the problem like the objective function. Next to
fixedvolume_soup.mlx file. The function inputs will appear. Select
Constraints, use the dropdown menu to specify where the function is
radius for the first input and height for the second input.
defined. You can define it on one line, or use a local function or function file.
View the contents of the function file:
When defining the constraint on one line, there is a dropdown menu to edit fixedvolume_soup.mlx
control how the left-hand side relates to the right-hand side, as an equality
or inequality. (<=,>=,=)
When defining the constraint with a local function, click the dropdown
menu to select the local function.
h ≤ 15 V (r, h) = 300
When defining the constraint with function file, click the Browse to file
button to link the function file to the task. You can then specify the Function
inputs, which can be the design variables.
Constraints can be added or removed from the problem by clicking the plus
or minus buttons.
h
r≥0
h≥0
View the cost function as a surface above the feasible region in the
With two design variables, the objective function can be thought of as a
radius-height plane.
surface above the design-variable plane. The optimal solution is the point
in the plane corresponding to the lowest point on the surface. edit GeometricVisual.mlx
View the completed Live Task that solves this problem.
edit SoupSolution.mlx
For the soup can example, the feasible region is the curve (corresponding
to the fixed-volume constraint) within the shaded region (corresponding to
the height and radius constraints).
The optimal solution corresponds to the point in the feasible region that lies
on the contour with the lowest value.
Constraints limit the possible solutions to live within the feasible region – the
set of points in the design-variable space that satisfy the constraints.
g cost
asin
D ecre
Optimal solution
(approximate location)
Summary
• Optimization task
• Components of a problem
• The optimization process
Classify problem
Variables Objective Constraints
Choose solver
Algorithm Options
Run optimization
Evaluate results
Stop ☺ Modify and Repeat
2. What are valid formats for an objective function for use in the Live Script
optimization Task? (Select all that apply)
A. As a local function
B. As a function handle
C. As a symbolic equation
D. As a function file
3. Suppose a problem has five design variables. How are they represented
in MATLAB®?
A. Five scalars
B. A 5-element vector
C. A 5-by-5 matrix
D. A function handle to a function with five inputs
Specifying Objective
Functions and
Constraints
3 - 1
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Specifying Objective Functions and Constraints
Outline
• Objective function files
• Bounds and linear constraints
• Nonlinear constraints
solver objective
First, data is needed on the sun’s apparent position over time at the location
of the solar panel. In this case, there are cartesian coordinates of the sun’s
position as if it were at a unit distance from the panel.
Second, a metric is needed for measuring the difference between the solar
panel’s normal vector and the sun beam. Note that the position of the sun
changes, so the metric must take this into account. The metric used here is
the average power loss of the solar panel as the objective function. Loss is
equal to the sine of the angle between the normal vector of the panel and
the sun beam, which can be expressed in terms of their dot product or inner
product.
To account for multiple positions of the sun, take the average loss. This is
the objective function, where the three elements of the normal vector of the
solar panel are the design parameters.
Types of Constraints
In this chapter requirements are added to the solar panel optimization: Lower Upper
• The solar panel should not point towards the ground, and point above Bounds Panel must point Panel must tilt
trees.
above trees. enough to allow
• The panel should also be tiled enough to allow snow to slide off. snow to slide off.
• The panel should point in the general direction of the sun.
• The normal vector should have a unit magnitude.
Bounds limit the possible values of the design variables to specified ranges. Constraints
Constraints can be classified as either linear or nonlinear and either equality
or inequality constraints. Constraints are linear if they can be written as Linear Nonlinear
weighted sums of design variables in the constraint expression. If not, they Normal vector must
are classified as nonlinear. Equality
have unit magnitude.
Panel must not face
Inequality
away from the sun.
Define the design variables, the elements of the normal vector of the solar
This chapter introduces the MATLAB® problem-based workflow. Start
panel.
by creating a set of optimization variables (design variables), and an
optimization problem object. Specify the details of the objective function panelnorm = optimvar("panelnorm", [3,1]);
and constraints by using the optimization problem properties. Define the objective, the average power loss of the solar panel, as an
optimization expression.
x = optimvar("x",[8,1]);
loss = mean(sqrt(1-(coords*panelnorm).^2));
The first argument is the name of the design/optimization variables. The
Specify the nature of the optimization problem to minimize power loss.
second argument is the size and shape of the variable. In this case, it is an
eight-by-one array. prob = optimproblem("ObjectiveSense","min");
Add the objective to the optimization problem.
Objective functions and constraints can be written as optimization
expressions using the optimization variables and numeric variables in the prob.Objective = loss
workspace. A possible form of a quadratic objective function: Show the optimization problem so far.
obj = x'*S*x; show(prob)
The solar panel power loss problem is set up. Try to solve it. First, specify
You can solve an optimization problem by using the solve function. The
an initial guess.
resulting design variables values and objective value represent a solution.
Depending on the nature of the problem, you may have to supply an initial x0.panelnorm = guess;
guess for the design variables. Then input the problem and the initial guess into the solve function,
and output the optimal normal vector of the panel, along with the
x0.x = ones(8,1)/8;
[xvals,objval] = solve(prob,x0)
corresponding loss.
[optnorm,lossSol] = solve(prob,x0)
The solve function accounts for the properties of the optimization
You may check the result visually using the helper function
problem that is input, and chooses a solver automatically that suits the
plotSunTrajectory.mlx.
problem. How to choose this and other properties manually is discussed in
the next chapter. plotSunTrajectory(coords,optnorm)
Note that no constraints have been implemented in the minimization of If no solver is specified by the user, then MATLAB will automatically
the objective. The result here may seem suboptimal. choose a solver that best suits the problem, in the problem-based approach.
Solver choice is discussed more in the next chapter.
To ensure the solar panel does not face the ground and above the nearby
Bounds are expressed using two values or two vectors, one for the lower
trees, you set a lower bound for the z-coordinate of the normal vector
bounds and one for the upper bounds. If the corresponding design variables
upon creating design variables. Use the angle of the tree tops forest as
are written as a vector, each upper and lower bound vector must be the same
the lower bound.
size.
To allow heavy snow to slide off of the protective glass layer of the solar
For variables that do not have a lower or upper bound, you may set the panel, the normal vector of the panel has to be sufficiently tilted away
corresponding element to –inf or inf, respectively. Each element of the from the z-axis. Use the value derived from the coefficient of static friction
lower bound vector must be strictly less than the corresponding element of friction as the upper bound.
the upper bound vector.
panelnorm = optimvar("panelnorm",[3,1],...
The functions zeros and ones may be useful for creating vectors of "LowerBound",[-inf;-inf;forest],...
bounds in case some design variables have the same bounds. You can also "UpperBound",[inf;inf;friction]);
input one scalar value which is implicitly expanded into a vector to match Redefine the objective function optimization expression and problem in
the size of the design variable vector. terms of the new bounded panelnorm variable.
prob.Objective = ...
You can set bounds upon creating the optimization variables, or after the
mean(sqrt(1-(coords*panelnorm).^2));
fact by changing the properties of the optimization problem.
Does this constraint change the result? Check by solving the optimization
w = optimvar("w",[8,1],... problem again.
"LowerBound",0,"UpperBound",0.25)
[optnorm,lossSol] = solve(prob,x0)
prob.Variables.w.LowerBound = 0;
prob.Variables.w.UpperBound = 0.25; Check this result visually with the helper function.
plotSunTrajectory(coords,optnorm)
0 w1 0.25
0 w2 0.25
.. ≤ .. ≤ ..
. . .
0 wn 0.25
lb w ub
Since the objective function uses the square of the inner product between
A linear combination of the design variables can be written as a vector dot
the solar panel normal vector and the position of the sun, it is possible that
product using matrix-vector notation:
there are optimal solutions where the panel is facing away from the sun.
x1 To avoid getting an incorrect solution, constrain the solar panel to face
x2 towards the average position of the sun by making the inner product
a1 x1 + a2 x2 + · · · + an xn = a1 a2 ··· a n . = aT x
.. between them non-negative.
xn
avgcoord = mean(coords);
prob.Constraints.SunSide = ...
Thus, any linear equality or inequality constraint can be written in the form avgcoord*panelnorm >= 0;
Aeq x = beq or Ax ≤ b , where A is a vector or matrix of coefficients, x is the
vector of design variables, and b is a scalar constant or vector of values. Solve the problem and visualize the results.
[optnorm,lossSol] = solve(prob,x0)
Multiple linear constraints can be written in this form, where Aeq is a matrix plotSunTrajectory(coords,optnorm)
and beq is a vector. Each row of Aeq represents the coefficients for a different
constraint. Each element of beq is the corresponding constraint value. For c
constraints, Aeq is c -by-n and beq is c -by-1.
You may have multiple constraints (and the objective) implemented in the
same function file. If a constraint or objective function is simple enough,
you can write it purely as an optimization expression.
[p,q] = fcn2optimexpr(@constraints,x,R,S,...
"ReuseEvaluation",true)
prob.Constraints.cons5 = p == 4;
prob.Constraints.cons6 = q <= 0;
If there are two outputs to your function, you can ask for two outputs
from fcn2optimexpr. The outputs to the function handle are given
corresponding optimization expressions in the workspace.
[obj2,const] = fcn2optimexpr(@objective,x,y);
objective.mlx
function y = objective(x)
. . .
Summary Try
• Objective functions To see the Problem-based Live Task for this problem, open and run the
• Bounds and linear constraints file LiveTask_SolarPanel.mlx
• Nonlinear constraints edit LiveTask_SolarPanel.mlx
Solvers and
Performance
4 - 1
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Solvers and Performance
Outline
• Classifying the problem and objective
10
• Choosing an algorithm 8
• Setting tolerances 0
-2
-4
-8
2
1 2
1
0
0
-1
-1
-2 -2
3 0.7 10
2.5 0.6 8
2 6
0.5
4
1.5
0.4
2
1
0.3 0
0.5
-2
0.2
0
-4
-0.5 0.1
-6
-1 0 -8
1 1 2
0.8 1 0.8 1 1 2
0.6 0.8 0.6 0.8
1
0.6 0.6 0
0.4 0.4
0.4 0.4 0
0.2 0.2 -1
-1
Linear/Cone
0.2 0.2
0 0 0 0 -2 -2
90 200
100
80 150
100
70
80 50
60 0
50 60 -50
-100
40
-150
40
30 -200
20 -250
20
-300
10 5
-5
0
0
0 0
0 5 10 15 20 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 -5 5
Set up the problem to maximize revenue for the hydroelectric dam. Open
We want to maximize the revenue of a hydroelectric dam. The price of
and run live script.
electricity and inflow are tracked hourly. Price is measured in dollars per
megawatt-hour ($/MWh), and inflow is measured in cubic meters per edit HydroProblem.mlx
second. We have the price and inflow time series data. So to maximize HydroProblem
revenue is a matter of controlling the turbine flow and spill flow of the dam This script creates the design variables, objective function and linear
over time. Both of these flows sum as project flow. constraints.
Design variables
After formulating an optimization problem mathematically, the first step
The turbine flow and spill flow tracked for every hour. in the optimization process is to classify it and, thus, choose an appropriate
solver. In the Problem-based approach, this step is performed automatically.
Objective function
The goal is to maximize the total revenue generated from selling electricity.
Constraints
The spill flow and turbine flow cannot be negative. Turbine flow cannot
exceed 710 m³/s. The minimum project flow is 14 m³/s. The change in flow
must be smaller than 14 m³/s per hour. The reservoir can store 6.1e7 m³
to 1.22e8 m³, and by the end of the day must have 1.1e8 m³. Also, place an
upper bound on the second derivative of turbine flow to limit how much
work the valve does to extend its life.
The objective function has an optimal point, given the imposed constraints.
For this problem, the optimal point is a spill flow and turbine flow schedule
Spill
that maximizes revenue for the hydroelectric dam.
→
→
Flow
Reservoir
In Flow Storage Project Flow
MATLAB® chooses a solver, in this case fmincon, based on the form of this Turbine →
objective function and the constraints. A solver is an Optimization Toolbox™ Flow
function that solves a certain class of optimization problems. Optimization
routines such as fmincon are iterative, evaluating the objective function Electricity
repeatedly during the optimization process.
Run the optimization problem and plot the resulting flow schedule using
For general optimization problems fmincon is a good solver. However, in
the helper function makeHydroPlot.mlx.
this case the objective function is quadratic and the constraints are linear.
This means we can use quadratic programming to solve the problem. Such [s,rev] = solve(prob)
problems have efficient solution methods that take advantage of the simple makeHydroPlot(s.SpillFlow,s.TurbineFlow,...
structure of the problem. inFlow,price,store0,k1,k2)
Note from the output that the solver chosen by MATLAB is quadprog.
Using the solver that is best fitted to the problem can significantly increase You can manually choose the fmincon solver by providing an initial
the efficiency of your code. In this case, the solver quadprog is chosen guess and specifying the solver with the Solver name-value pair.
automatically.
[sf,revf] = solve(prob,s,"Solver","fmincon");
There may be numerous methods, or algorithms, you can use to solve a
given class of problem. Each solver in Optimization Toolbox therefore has
different available options, including which algorithm to use.
Classify problem
Variables Objective Constraints
Minimizes Minimizes specific
Choose solver any f (w) form for f (w)
Algorithm Options
Specific form
Evaluate results
for f (w)
Stop ☺ Modify and Repeat
Constraints
can be written in the form f (x) = ( 12 )xT Ax + B T x, where a is an n-by-n lsqlin lsqnonlin
matrix and b is an n-by-1 vector. Bounds lsqnonneg lsqcurvefit
Most of the Optimization Toolbox solvers, including fmincon, assume that Linear lsqlin fmincon
the design variables can take any value, subject to the constraints. Integer
programming problems form an important class of optimization problems Nonlinear fmincon fmincon
in which the variables are required to have discrete (integer) values, as well
as further constraints. A common specific application of minimization is least-squares fitting, such
as fitting a curve to data. In this case, the objective function is of the general
form
Objective Function
f (c) = F (c)2 = Fk (c)2
Linear Quadratic General k
fminsearch
None N/A quadprog where f is a function defined by the parameters c. In the case of curve
fminunc
fitting, f has a specific form representing the error between the curve and
quadprog fminbnd
Constraints
Use the tables here to guide your choice of solver, based on the objective type
*Some quadprog problems can be converted into coneprog problems. and the form of the constraints. In the Problem-based approach this choice
is made automatically. You can also specify a solver explicitly. Computation
Note that only the solvers fmincon and fminunc will be used to
time can be measured using the tic and toc functions.
evaluate a problem when fcn2optimexpr is involved in the setup of the
optimization problem.
To extend the life of the valve for turbine flow, we place an upper limit on
By default, solvers provide a summary message when they terminate that
the amount of work the valve does.
explains whether the optimization was successful. You can also get more
detailed diagnostic information as extra outputs from the solver function: prob.Constraints.Stress = ...
diff(diff(TurbineFlow)).^2 <= 64;
[x,f,flag,output] = solve(problem);
This is a nonlinear constraint. This forces MATLAB to use fmincon as
double(flag)
the solver. So we must supply an initial guess for the design variables.
The termination flag summarizes the reason the solver terminated. s0.TurbineFlow = 10*ones(size(TurbineFlow));
• A positive value means that a solution is found successfully. s0.SpillFlow = zeros(size(TurbineFlow));
• A negative value indicates a problem. Additional output arguments can be retrieved to gather diagnostic
information, like the termination flag.
• A value of 0 means that a solution was not found before the iteration
limit or function evaluation limit is reached. [s,rev,flag,output] = solve(prob,s0);
double(flag)
For a detailed description of the meaning of flag, see the documentation Plot the resulting flow schedule.
for your specific solver.
makeHydroPlot(s.SpillFlow,s.TurbineFlow,...
inFlow,price,store0,k1,k2)
output
<0 0 >0
fminunc lsqlin
• If your objective function does not return a gradient, use • If you have linear constraints, use active-set.
quasi-newton.
coneprog
quadprog • Uses interior-point [default].
• Use interior-point-convex [default] first.
• If you have only bounds or only linear equality constraints (but not
both), use trust-region-reflective.
• Use active-set if problem is indefinite.
If one of the first three conditions occurs, the termination flag is positive. If
either of the last two conditions occurs, the flag is zero.
minimum
=⇒ f (x) = 0
Note that your objective function should not rely on the variables being
constrained precisely by given constraints. For example, an objective function f (x) ≈ 0
that calculates the square root of a variable may produce a complex result close enough?
even if that variable is bounded below by 0. As well as that variable possibly
being slightly negative, within the bounds of ConstraintTolerance,
some algorithms allow intermediate iterations to violate the constraints.
You can see the information graphically by setting the "PlotFcn" option.
The value of this option should be a function handle or string to the plotting First-order Norm of
function you want to use. Generally this is one of the predefined functions Iter F-count f(x) Feasibility optimality step
0 93 -1.154441e-02 4.441e-16 1.001e-01
provided with Optimization Toolbox: 1 186 -1.184680e-02 5.551e-16 1.006e-01 5.942e-04
2 279 -2.904327e-02 2.220e-16 3.422e+00 3.636e-02
• optimplotx to see the values of the design variables 3 372 -4.082861e-02 2.220e-16 1.989e+00 3.401e-02
4 465 -4.335443e-02 1.110e-16 1.723e+00 1.441e-02
• optimplotfval to see the value of the objective function 5 558 -4.576117e-02 2.220e-16 5.829e-01 1.655e-02
• optimplotfirstorderopt to see the value of the first-order 6 651 -4.807888e-02 0.000e+00 2.648e-01 1.951e-02
7 744 -5.037998e-02 0.000e+00 7.291e-01 2.438e-02
optimality measure. 8 837 -5.172487e-02 1.110e-16 5.193e-01 2.176e-02
• optimplotfunccount plots the function count. optimoptions(...,"Display","iter")
• optimplotconstrviolation plots the maximum constraint
violation.
Open and run a script that solves this problem which has integer design
Another way to harvest solar energy is with concentrated solar power, using
variables, bounds and linear constraints.
solar power towers. An array of adjustable mirrors known as “heliostats” are
situated around a target tower. The heliostats follow the sun throughout the edit SolarPowerTower.mlx
day, directing sunlight to the top of a tower to flash steam water. The steam SolarPowerTower
is then used to generate electric power using a turbine.
Objective functions
Design variables
Maximize revenue given that we have time series data taken at regular
The number of heliostats directing sunlight to the target tower over time,
intervals on solar irradiance and electricity price during three different
and the temperature of the water in the tower. There can only be an integer
days.
amount of heliostats pointed at the tower.
For some problems you may have discrete design variables. If your
Constraints
objective function and constraints are linear as well, then MATLAB
There is a limited amount of land for heliostats. The temperature of the
chooses the intlinprog solver. The Optimization Toolbox provides the
target is held within a range as to steam water but not melt the tower. The
intlinprog solver for linear integer programming. This solver allows for
amount of energy delivered to the target converts the maximum amount
mixed integer linear problems: where some design variables are integers,
of water into steam. The change in the amount of heliostats pointed at the
while others may be continuous. For these type of problems, the objective
target is limited to reduce gimbal wear.
function can be expressed as f (x) = AT x, where A is an n-by-1 vector.
v = optimvar("v",[4,1],"Type","integer")
Target
Tower The algorithm used by intlinprog uses continuous variables that are
restricted to integer values at each step. For the sake of efficiency, this
Heat water to restriction is performed to within a specified tolerance. This means that the
generate steam solution values are not necessarily exact integers. Use optimoptions to
Sunlight set the IntegerTolerance option, if more or less precision is required.
Heliostats
Summary
• Classifying the problem and objective
10
• Setting tolerances 0
-2
-4
-8
2
1 2
1
0
0
-1
-1
-2 -2
nonlinear Y
constraints fmincon
?
N
number of >1
design variables
Y Y
constrained constrained
? ?
fminbnd N N
fminsearch fminsearch
fminunc fminunc
Global and
Multiobjective
Optimization
5 - 1
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Global and Multiobjective Optimization
Outline
• Using multiple starting points
• Derivative-free methods
• Minimizing multiple objective functions
x0 x0 x0 x0
Open and run a script that solves this problem, which has integer design
Here you will build upon the Solar Power Tower example of the previous
variables, bounds, linear and nonlinear constraints.
chapter. The goal is to see if a higher revenue is possible using global
optimization techniques. You can use genetic algorithm or surrogate edit SolarPowerTowerNL.mlx
optimization, which allow for integer design variables. You will keep the SolarPowerTowerNL
amount of heliostats an integer as was done in the previous version of this With the problem-based approach taken, MATLAB automatically chooses
problem. the genetic algorithm solver for this problem, given the constraints and
bounds. This may take approximately five to ten minutes to run. So a
Additional design variables and constraints have been added to this
solution file is provided here.
problem, making it nonlinear. The rate at which water is pumped is turned
into design variable with bounds and linear constraints on it. One of the load NLSolution.mat
previous constraints on heat now becomes nonlinear as a result of this HelioSchedulePlots(s.N,s.Temp,s.Pump)
change.
Target
Tower
Heat water to
generate steam
Sunlight
Heliostats
Derivative-Free Optimization The is an example in the documentation of direct search optimization using
Mount Washington topography.
Even when derivative information is not supplied, classical solvers such as openExample("globaloptim/mtwashdemo")
fmincon still rely on the assumption that the objective function has smooth
derivatives. If the objective function is not smooth, including the case that
the objective has a stochastic (random) component, classical methods may
not provide adequate solutions. In this case, use a derivative-free solver, such
as a direct search method, genetic algorithm or surrogate optimization.
Open and run a script that compares the results of genetic algorithm and
Surrogate optimization has two phases. The first is construction of a
surrogate optimization. This takes about ten minutes to run.
surrogate. This is where random points are created within the bounds of
the problem. Then the objective function is evaluated at those points. Then edit SolarPowerTowerGS.mlx
interpolation between these points is implemented via radial basis functions,
resulting in a surrogate of the objective function. The second phase is the Sample random points from
search for the minimum. Random points created within surrogate. Chose best point
bounds. (adaptive point).
• Several random points are sampled from within the bounds of the
problem.
• A merit function is applied, based on the surrogate value at the sample
points.
• The best point is chosen as a candidate by the merit function value. This
is known as the adaptive point.
• The objective function is then evaluated at this point. This value is then
used to update the surrogate at that point.
This process repeats. Points are sampled near the incumbent point, the merit
is evaluated, the best point is selected, objective is evaluated there, and the
interpolant is updated accordingly. This continues until the points sampled
are close to the points where the objective was previously evaluated.
Open and run a script that solves the solar power tower problem using the
A simple way to find a global minimum is to perform multiple
MultiStart solver. Note that the integer constraint on the number of
local minimizations, starting from different locations. You can use
heliostats is relaxed. Instead, these numbers are rounded and the values
GlobalSearch and MultiStart solvers to search from multiple
are checked after the fact.
starting points.
edit SolarPowerTowerMS.mlx
To use either algorithm, GlobalSearch uses a scatter-search mechanism
to create starting points. MultiStart creates uniformly distributed start
points within the bounds, or uses user-supplied start points. GlobalSearch MultiStart
Use to efficiently find a global min- Use to find multiple minima, to run
GlobalSearch analyzes starting points and selects the ones likely to imum (on a single processor). in parallel, or to use a solver other
improve the best local minimum found so far. MultiStart runs all start than fmincon.
points, or all points feasible within constraints if the user specifies as such. Selectively samples starting points Runs from all prescribed starting
points
The following command creates a GlobalSearch solver variable gs that
uses default options for the global search algorithm. Cannot be run in parallel Can be run in parallel
gs = GlobalSearch("NumStageOnePoints",100);
The outputs from solve when using GlobalSearch are essentially the
same as from a single solver such as fmincon.
[x,f] = solve(problem,guess,gs);
Use the same process to create and use MultiStart solvers. When using
Local minimum
the solve function, you must provide either the number of starting points, or
the starting points themselves.
Global minimum
x0 x0 x0 x0
© 2023 by The MathWorks, Inc. Optimization Techniques in MATLAB® 5 - 8
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Global and Multiobjective Optimization
As with intlinprog, you can specify the indices of the design variables Property Name Description
that are required to be integers. However, ga can handle nonlinear objective PopulationSize Number of individuals in the
Population Parameters
functions and nonlinear constraints. The ga and gamultiobj functions population at each iteration.
provide default crossbreeding and mutation functions, and default settings EliteCount Number of individuals selected as the
for various parameters, such as population size and the convergence elite at each iteration (see description
tolerance. You can provide your own functions and set your own values of on next page).
all the parameters using optimoptions.
CrossoverFraction Fraction of parents
In multiobjective optimization, the result is often not a singular solution. (PopulationSize-EliteCount)
Instead, the result is a set of solutions along a Pareto front curve. A user that reproduces by crossbreeding. The
can then choose a point from the Pareto front arbitrarily, unless there is an remainder reproduce by mutation.
CreationFcn Function that creates the initial
Functions
inflection in the curve, in which case the inflection point is typically chosen.
population.
CrossoverFcn Function that generates children from
parents by crossbreeding.
MutationFcn Function that generates children from
parents by mutation.
FitnessScalingFcn Function that scales fitness values
before the selection process.
SelectionFcn Function that chooses which (non elite)
The goal attainment fgoalattain solver is a specific way of avoiding individuals become parents.
arriving at multiple solutions. This formulation allows objectives to be
achieved with relative precision around user-specified goals. The user
supplies a weighting vector, where each element corresponds to a goal, Goal attainment can be used as a hybrid function with gamultiobj for
and indicates the percentage of precision for that goal. The third output some problems to further optimize the Pareto front.
argument gives the attainment factor. If it is negative, the goals have been
overachieved, if positive, they have been underachieved. options = optimoptions("gamultiobj",...
"HybridFcn","fgoalattain")
Solver Choice
When looking for a global minimum (or maximum), use these steps to try If there are multiple objective functions, there is another set of solvers to try:
solvers: 1. For a single solution try fgoalattain or fminimax. Both can
1. Try GlobalSearch first, to find global solution using local solver handle bounds, linear and nonlinear constraints. They arrive at a single
fmincon. solution using the goal attainment problem formulation. The first has
2. Next try MultiStart. Uses local solvers on variety of start points. user-supplied weights and minimizes a slack variable, and the second is
unscaled: minimizing the maximum objective.
3. Try patternsearch. Robust but less efficient as no gradient used.
Provably converges on nonsmooth problems. Can handle all constraint 2. For a set of solutions, try paretosearch or gamultiobj. The first
types. uses patternsearch, the second uses ga to arrive at a Pareto front.
4. Try surrogateopt. Find global solution using fewest objective
function evaluations. More overhead than other solvers. Requires
finite bounds. Can have integer constraints and nonlinear inequality
constraints. For problems that have time-consuming objective functions. Objective and Constraints
5. Try particleswarm next, if the problem is unconstrained or has Smooth Nonsmooth
bounds. Little supporting theory, but more efficient than patternsearch. Single linprog, quadprog fminbnd, fminseach
6. Try ga next. It can handle all constraint types, including integer constraints. local fmincon, fminsearch patternsearch, ga
Little supporting theory, and less efficient than patternsearch and solution fminbnd, intlinprog particleswarm
particleswarm. lsqcurvefit,... simulannealbnd
surrogateopt
7. The last to try is simulannealbnd. Can have unconstrainted and
Desired Solution
unbounded problems. Only takes bound constraints. Least efficient Multiple GlobalSearch patternsearch, ga
local MultiStart particleswarm
solver. Provably converges, but extremely slow.
solution simulannealbnd
surrogateopt
Single fgoalattain Single GlobalSearch patternsearch, ga
Desired Solution
Summary
• Using multiple starting points
• Derivative-free methods
• Minimizing multiple objective functions
x0 x0 x0 x0
Conclusion
6 - 1
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Conclusion
Course Summary
Day 1
• Introduction
• Running an Optimization Problem
• Specifying the Objective Functions and Constraints
• Choosing a Solver and Improving Performance
• Global and Multiobjective Optimization
• Conclusion
Appendices
• Exercises
• Extra Examples
Products and services You should create a MathWorks account by selecting the Log In link in
• Product information the mathworks.com navigation bar and then selecting the Create
Account link on the next page. A MathWorks account will allow you to
• Training schedule view information about your product licenses, receive technical support,
and participate in the MathWorks community.
Support
• View and report bugs
• Documentation
• Download products
• Products & services home • View and report bugs • Create MathWorks account
Community
• MATLAB Answers • Training schedule • Documentation • Manage your account
• File Exchange • Consulting offerings • Downloads • Obtain product updates
• Cody
Events
• Webinars
• Seminars
• Conferences and tradeshows
Additional Resources
With a MathWorks account, you can request technical support, report
product bugs, and submit product enhancement requests from the
MathWorks web site at www.mathworks.com.
Set the request type to Technical Support and then choose a specific
category of support. Now you can enter the information describing your
request and submit it to technical support.
To view known bugs and recommended workarounds, you can refer to the
Bug Reports page at the link below.
www.mathworks.com/support/bugreports/
Please take a moment to fill out a brief course evaluation. When completing
the evaluation, enter the email address that you used to register for this
course.
Appendix A:
Exercises
A - 1
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Appendix A: Exercises
Exercises
All exercise and solution files are found in the Exercises subfolder
of the C:\class\coursefiles\mlop folder created by the course
installer.
Loan Rate I ................................................................. A-3 Chapter 2 Loan Rate III .............................................................. A-19 Chapter 4
Minimizing a Mathematical Function .................... A-4 Chapter 2 Minimizing a Mathematical Function II ................ A-20 Chapter 4
Optimal Cabin Construction I ................................ A-5 Chapter 2 Using Hessian Information ...................................... A-21 Chapter 4
Optimize a Portfolio .................................................. A-6 Chapter 2 A Catenary Curve ...................................................... A-22 Chapter 4
Loan Rate II ................................................................ A-7 Chapter 3 Chip Production II .................................................... A-23 Chapter 4
Projectile Range ......................................................... A-8 Chapter 3 Plant and Storage Location....................................... A-24 Chapter 4
Global Positioning System ....................................... A-9 Chapter 3 Mars Orbit Prediction................................................ A-25 Chapter 4
Vapor Pressure ........................................................... A-10 Chapter 3 Efficient Frontier ....................................................... A-26 Chapter 4
Air Conditioning I ..................................................... A-11 Chapter 3 Weber’s Problem ........................................................ A-27 Chapter 5
Chip Production I .................................................... A-12 Chapter 3 Hunter’s Riddle .......................................................... A-28 Chapter 5
Mean-Gini Portfolio Optimization ......................... A-13 Chapter 3 Chip Production III .................................................. A-29 Chapter 5
Optimal Cabin Construction II ............................... A-14 Chapter 3 Optimal Cabin Construction III ............................. A-30 Chapter 5
Optimize a Portfolio II .............................................. A-15 Chapter 3 Plant and Storage Location II ................................... A-31 Chapter 5
A Manufacturing Process ......................................... A-16 Chapter 4 Mars Orbit Prediction II ........................................... A-32 Chapter 5
Estimating Model Parameters .................................. A-17 Chapter 4 Optimize a Larger Portfolio ..................................... A-33 Chapter 5
Air Conditioning II ................................................... A-18 Chapter 4
Exercise
Compute the remaining balance of a $100,000 loan at 3% nominal annual
interest rate after 10 years for a given monthly payment. The goal is to
determine a monthly payment such that the loan has been paid back at the
end of the 10 years. You can do this by
• solving Balance(payment) = 0 or
• minimizing (Balance(payment))^2.
Exercise
Find the minima in the following problem using the Optimization Live Task
Exercise
Exercise
g
V
h
r(θ, v, h)
The position of an object should be determined using data provided by 5. Create the optimization variables with upper and lower bounds for each
three satellites. To this end, write a function according to the following variable.
specifications: 6. Write the nonlinear constraint(s) as an optimization expression.
1. The objective function should have the following variables:
– p: A 3-element vector containing 3-D position of object.
– satData: A structure variable with fields p21 + p22 + p23 ≤ 40,411,449
−6357 ≤ p1 ≤ 6357
• xPos: 3-element vector of x-coordinates of each satellite
−6357 ≤ p2 ≤ 6357
• yPos: 3-element vector of y-coordinates of each satellite −6357 ≤ p3 ≤ 6357
• zPos: 3-element vector of z-coordinates of each satellite
• dist: 3-element vector of distances from object to each satellite
2. For each satellite, the function should calculate the error given by:
3. The objective function should return the sum of the errors for each
(xP os − p1 )2 + (yP os − p2 )2 + (zP os − p3 )2 − dist2
Exercise
This exercise finds an equation of state for some measured ethanol data. The
equation for pressure as a function of temperature is:
log Pvap (T ) = A log T + B/T + C + DT 2
If the air conditioning is running at x percent, the power usage has been
found to be f(x) = 2.4087*x.^3 - 3.5839*x.^2 + 2.1752*x
as a fraction of maximum power usage.
1. Write an objective function that accepts an optimization variable vector
of AC usages as an input and returns the total power consumption. The
total power consumption is computed by evaluating the above f(x) for
each component of the input vector and summing the results.
2. Load AC_test.mat and test your objective function with different
scenarios using the evaluate function.
• AC_Usage1: AC is off all the time.
• AC_Usage2: AC runs at full power all the time.
• AC_Usage3: AC runs low at night, high during day.
Exercise
5. The upper-right corner of the uppermost, rightmost chip must be within
When placing chips on a silicon wafer, you want to minimize the area of the limits of the wafer.
the disk that is not occupied by a chip. The following steps will guide you
through a preliminary implementation of the corresponding optimization
problem.
1. Import the optimization problem parameters from the file
chipParams.mat. This file contains a structure with the following
fields:
– radius (of the wafer), set to 600 mm
– width (of the chip), set to 40 mm
– height (of the chip), set to 35 mm
2. Use the params structure and the existing function
chipObjective.mlx to define a function handle that can be
converted into an optimization expression and added to the problem.
3. Assume that the center of the wafer is at the origin of a 2-D set of axes.
The chip placement is defined by the coordinates of the upper-right
corner of the uppermost, rightmost chip on the disk. This is based on
the assumption that all other chips are tightly packed around and aligned
with this first chip. Define the initial chip coordinates to be
√
x0 = 0.5 · radiuswafer · 1 1
Apply the following constraints for the two design variables, which are the
x- and y-coordinates of the upper-right corner of the uppermost chip in the
rightmost column on the wafer:
4. The center of the uppermost, rightmost chip must have nonnegative
coordinates.
Exercise
In this exercise, you will specify bounds and linear constraints for a portfolio
optimization problem. The mean-Gini portfolio optimization model
provides an alternative to standard mean-variance portfolio theory. The
latter assumes that asset returns come from a normal distribution, whereas
the mean-Gini framework is independent of the asset return distribution.
where S = RwT is the vector of overall portfolio returns, and F (S) is the
cumulative distribution function (CDF) of S .
1. An implementation of this objective function can be found in the file
portGiniObj.mlx, and sample historical return series for N = 6
stocks are stored in mgPortData.mat. Create an optimization
problem with a function handle for portGiniObj.mlx as the
objective function, and with the data from mgPortData.mat. Use
the fcn2optimexpr function. The design variables are the portfolio
weights.
2. The portfolio weights w1 , w2 , …, wN must sum to one, and the mean
portfolio return, given by mean(portReturns), must be a fixed
constant (0.0084). Classify these types of constraints.
3. Impose portfolio diversification constraints: any given stock must not
exceed 40% of the overall portfolio, and any given stock must not form
less than 0.4% of the overall portfolio. Classify these constraints.
Exercise
Exercise
1. Load StockInfo.mat into the MATLAB workspace.
2. Specify the risk-free rate as: RFrate = 1.0228^(1/250)
3. Use optimvar to create the weight/allocation design variable. Impose
bounds here such that weights are positive and no greater than 0.25.
4. Create optimization expressions defining portfolio risk, return and
Sharpe ratio.
5. Use the optimproblem function to create an optimization problem
with an objective sense to maximize the objective.
6. Make the Sharpe ratio expression the objective function of the problem.
7. Add constraints to the problem:
• The weights must sum to 1.
• The risk must be no greater than a threshold (standard deviation ≤ 0.02)
• No more than 40% of the stocks in the portfolio can come from any one
country. (The first 3 stocks are US, the next 3 are Australian, the last 2
are German.)
8. Supply an intial guess for the weights, run the optimization and visualize
the optimal allocation using the helper function threshpie.mlx.
In this exercise, you will determine the parameters of a model that best
match observed data. In particular, you will estimate the volatility of Apple
stock using the Black-Scholes model and option pricing data.
1. Load the data contained in AppleOpts.mat and visualize it with the
commands
plot(Strike,Ask,".")
xlabel("Strike Price")
ylabel("Option Price")
2. The Black-Scholes model asserts that the option price is determined from
the strike price via the calculation performed inside the BSprice.mlx
function file. Plot several curves representing the predicted option price
using the command
plot(Strike,BSprice(Strike,v,0.0005))
vol0 = 0.7;
RFrate0 = 0.3;
Exercise
In this exercise, you will deal with this and also check whether the
optimization was successful for each interest rate.
1. Replace the objective function from “Loan Rate II” with a function
handle that uses the abs function and use fcn2optimexpr function
to add it to the problem.
opts=optimoptions("fmincon",...
"SpecifyObjectiveGradient",true,...
"SpecifyConstraintGradient",true,...
"CheckGradients",true);
4. Measure how long it takes to execute the optimization with and without
the gradient check.
5. Open the generated function files containing the gradient information.
edit generatedConstraints.m
edit generatedObjective.m
6. (Bonus) Use custom function files to specify gradients.
edit simpleObjWGradient.mlx
edit simpleNLConsWGradient.mlx
In this exercise, you will supply an optimization routine with second order H = computeHessian(x, lambda)
derivative information in addition to the gradient. Second order derivative
information is captured in a Hessian matrix. The Hessian matrix associated where H is the Hessian matrix, x is a vector of design variables, and
with a scalar function, L, has entries lambda is a structure with fields
∂2L
HL (i, j) = lambda.ineqnonlin: a vector containing λi
∂xi ∂xj
lambda.eqnonlin: a vector containing λeqi
For a general optimization problem, define the Lagrangian as the function
In the body of the computeHessian function, define H as
L(x) = f (x) + λi ci (x) + λeqi ceqi (x),
H = (H for obj) +
lambda.ineqnonlin*(H for constraint)
where f (x) is the objective function, ci (x) are inequality constraints, ceqi (x)
B. Modify the optimization options structure from the last exercise with the
are equality constraints, and λi and λeqi are scalars known as Lagrange
command
multipliers. It follows that you can write
opts = optimoptions(opts...
HL = Hf + λi Hci + λeqi Hceqi 'HessianFcn',@computeHessian);
3. Run the optimization using fmincon and the opts structure defined
1. Compute, manually, the 2-by-2 Hessian matrix of the Lagrangian above. Do you notice a decrease in execution time compared to only
associated with the optimization problem presented in the Minimizing supplying gradient information?
a Mathematical Function II exercise and modified in the Using Gradient
Information exercise.
Note that, for this particular problem, only the associated objective function
and one inequality constraint have a nonzero second derivative. Therefore,
you can write
HL = Hf + λHc
You will use different options on the above problem and time them to
determine which is fastest.
1. Set up the problem such that the optimization variables are the positions
of each link in the chain. The objective function is the energy. The
constraints are the position of the endpoints of the chain.
2. Use optimoptions to choose sqp for the Algorithm. This solver
should be appropriate for the above equations since they are quadratic
in the point positions. Observe the run time for this method with tic
and toc.
3. Convert problem to solver-based using the prob2struct function.
4. Next, switch the SpecifyObjectiveGradient flag to true in
the next code section using optimoptions. Adding the gradients
results in a significant improvement.
Suppose there are a number of plants with static geographic positions. The storage locations should also be within the same district as the plants. In
Raw material is transported between each plant and the different storage this district there are 5 plants. The goal is to place 3 storage locations within
locations. the district, and determine how much material to transport, such that the
cost is minimized.
1. Write the objective function: 4. Solve the problem and plot the resulting locations with the
The cost of transporting this material is proportional to the distance plotPlantsAndStorageLocations function. Set the optimization
travelled d and quantity of material w. The goal is to minimize the cost. options to display output during the optimization process.
For security, the distance between any given plant and storage location must
be 2 km or greater.
To get a craft from Earth to Mars, a maneuver known as a Hohmann transfer 5. Use optimoptions to display iterations and plot function value and
can be used to preserve fuel. The sun is treated as a central gravitational design variable values.
body, and the craft goes from Earth’s orbit to an elliptical orbit around the
sun, such that it intersects with Mars’ orbit just in time to enter the planet’s 6. Plot the argument of the perifocus data and the predicted values
gravitational range on influence. This trip requires precise timing and together.
accurate prediction of the relative positions of bodies. To predict position
variables over time, curve fitting can be used: particularly minimizing the
error between data and a parametric function.
plot(MarsData.tsc,MarsData.W,"b-")
3. The objective function is the error (root mean square) between the
fitted parametric curve and the real data points. So the curve predicts the
position of Mars.
Exercise 7. Use the tic and toc functions to time how long it takes the for-loop
The efficient frontier is the curve of points in the “reward-risk” plane that to run. Take note of the solver used by default (fmincon).
represents the least risky portfolio possible for a given reward. You can find 8. Plot these values with the risk and reward of each stock.
the efficient frontier by stepping through a range of values for the portfolio 9. Change the objective function to be the square of risk. This will change
return, and minimizing the standard deviation (risk) of the portfolio for the default solver to quadprog.
each (fixed) value of the return.
In this exercise, the objective function to minimize is the standard devia- 10. Time how long the for-loop takes to run with this solver.
tion, and the fixed return value becomes an equality constraint. Because
return is calculated as a weighted average, it is a linear equality constraint.
All allocations must be between 0 and 1, and they must sum to 1. The port-
folio return must equal a fixed value. This minimization problem is run
repeatedly for various values of fixed portfolio returns.
1. Load StockInfo.mat
2. Specify a range of fixed returns to inspect.
givenReturn = linspace(min(R),max(R),200);
3. The design variables for this problem are the allocations, or weights, of
each stock in the portfolio.
4. The constraints are that the weights are positive and no greater than
1. The weights must also sum to 1. The return of the portfolio must be
equal to a given fixed return (this can be done within a for-loop).
5. The goal is to minimize risk for a given fixed return. The objective
function is risk.
6. Use optimoptions to turn off the display for the solver. Use a for-loop
to optimize risk for each value in givenReturn. You will then have a
minimum risk value for each return.
Exercise
A warehouse should be located near three store locations. There are two
stores at (-10, -10) and (5, 8) which need two truck loads per week and
a store at (25, 30) which requires one truck load a week. The warehouse
should not be located near the nuclear power plant at (0,0). It is equally
important to have the warehouse close to both of the bigger stores and to
stay away from the nuclear power plant.
An objective function for this problem takes the form of weighted distance:
4
f (x) = wi (x1 − zi1 )2 + (x2 − zi2 )2
i=1
Visualize the objective function using the evaluate function and the
contour plot function. Plot the geographic locations of all the facilities
with the contour plot.
Hints:
• This is an integer problem. Use genetic algorithms to solve it.
• Solving an equation A*x = b is the same as minimizing (A*x–b).^2.
Use this and total revenue being $100 to write the fitness function. Set
FitnessLimit=0 (Why? Can we do better?).
• Lower bound: 1 for each kind of animal (assumption that none is 0)
• Upper bound: The revenue from any kind of animal should not exceed
$100, no more than 100 animals of any kind.
• Creation function: Choose (reasonable) random integers for deer and
foxes and choose number of rabbits in order to have 100 animals total
• Mutation function: Make small random integer changes to the numbers
of deer and foxes (within the bounds) and choose rabbits accordingly.
• Crossover function: Randomly choose numbers of deer and foxes from
a parent and choose rabbits accordingly.
• Two subpopulations with 30 individuals each, simulated over a
maximum of 500 generations, should give you excellent results.
Exercise
x = optimvar("x",[1,2],"LowerBound",lb,...
"Type","integer")
3. Run the solve function and take note of the solver used.
4. Use the chipGraphics.mlx function file to visualize the solution.
chipGraphics(solution.x,"init",params)
Exercise
Minimize the cost of building a cabin, and maximize the volume of the
cabin. (Neglect the cost of doors, windows, etc.)
1. Open the file CabinSolution.mlx.
2. Add a second objective function characterizing cabin volume.
3. Use gamultiobj solver and plot the resulting Pareto front.
Exercise
Optimization Toolbox™ solvers for nonlinear problems, such as fmincon,
look for a local minimum, starting with a user-supplied initial guess.
Although you can verify that the returned solution is a local minimum, can
you determine whether it is the global minimum?
1. Run the solution from last Plant and Storage Location exercise:
setupPlantStorage.mlx which minimizes cost.
2. Convert the problem to a structure to use the solver-based approach.
3. Run global optimization solvers on this problem: GlobalSearch and
MultiStart with 60 starting points.
4. Plot the resulting storage locations using the
plotPlantsAndStorageLocations function.
Exercise
The fitted curve from the previous Mars Orbit Prediction exercise may not
be satisfactory. It appears there could be another sine function term.
Note that surrogate optimization is intended for problems that take a long
time to solve. There is an option that allows the user to save a checkpoint
file.
opts = optimoptions("surrogateopt",...
"CheckpointFile","checkfile.mat")
Exercise
The goal here is to a similar optimization to the one found in “Optimize a
Portfolio II”. However, this portfolio has more stocks, and less constraints
placed on it. You will change one of the constraints into a second objective
function to perform a multiobjective optimization.
1. Load FTSEStocks.mat
2. Specify the risk-free rate as: RFrate = 1.0228^(1/250)
3. Maximize the Sharpe ratio of the portfolio.
4. Limit the allocation sum to 1 and the risk to be no greater than 0.02.
5. Use the optimoptions function to tell the solver to use the sqp
algorithm, to display the iterations during solving, and to plot the
function value, design variable values and the first order derivative.
6. Run the solver and take note of the results.
7. Rework the problem such that there is no constraint on risk. Instead,
risk will become a second objective function to be minimized which the
Sharpe ratio is maximized.
8. Run the solve function, and plot the resulting Pareto front.
9. Choose a working point and compare the results to those of part 6.
Appendix B: Extra
Examples
B - 1
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Appendix B: Extra Examples
When run for a prescribed time span, the model returns the times and the
corresponding values of the angular acceleration θ̈ and vertical acceleration
z̈ .
Damping coefficient of front suspension Cf The following physical limitations are placed on the values of the four design
variables:
Stiffness of rear suspension Kr
1. Stiffness of front suspension 104 ≤ Kf ≤ 105
Damping coefficient of rear suspension Cr 2. Damping coefficient of front suspension 100 ≤ Cf ≤ 104
3. Stiffness of rear suspension 104 ≤ Kr ≤ 105
4. Damping coefficient of rear suspension 100 ≤ Cr ≤ 104
Kf Kr
Cf Cr
prob = optimproblem
prob.Objective = fcn2optimexpr(@discomfort, ...
[Kf, Cf, Kr, Cr], params)
For the car to be level when at rest, the springs must also satisfy the condition
L f k f = Lr k r
Nonlinear
0.3 ≤ cf
Lf + Lr
≤ 0.5 0.3 ≤ cr
Lf + Lr
≤ 0.5 Constraints
8kf · Mb · Lr 8kr · Mb · Lf
suspension.slx
Kf
Cf params
x=
Kr
t
Cr
Passenger
acceleration: z̈(t) θ̈(t)
a = (z̈ + rf · θ̈)2 + (z̈ − rr · θ̈)2
Discomfort: (max(a)+sum(a))/1000
© 2023 by The MathWorks, Inc. Optimization Techniques in MATLAB® B - 6
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es Coro Cantero - coro.cantero@tekniker.es
Appendix B: Extra Examples
Structure Make a structure, from the optimization problem, to use the solver-based
approach.
You can create a structure programmatically using the prob2struct >> ps = prob2struct(prob,x0)
function to convert from the problem-based approach to the solver-based
approach, or start with the createOptimProblem function.
You can test your problem structure by applying the appropriate local solver:
You can provide all the components of the optimization problem using
[x,f,flag] = fmincon(myprob);
parameter name-parameter value pairs. The table below lists the parameter
names for the problem components.
Note that when starting from the solver-based approach, that the objective
function is always minimized. So if you want to maximize it, you minimize
the negative of that function.
myprob = createOptimProblem("fmincon","objective",@myobjective,"x0",ones(n,1),"lb",zeros(n,1),...
"Aeq",ones(1,n),"beq",1,"options",optimoptions("fmincon","Algorithm","interior-point"));
Use the fmincon function to find the solution instead of solve. The
An objective function definition without a gradient has one output: the
change in syntax here is due to the problem becoming “Solver-based”
function value. If you are supplying a gradient to the solver this is specified
rather than “Problem-based”.
as the second output of the function.
>> [xOpt,fval,flag] = fmincon(ps)
function [val, grad] = Obj(x,c) >> visualizebump([xOpt(3); xOpt(1);...
val = mean(1-(c*x).^2); xOpt(4);xOpt(2)],params)
grad = -2*mean(c*x.*c);
To supply this to the solver, supply an anonymous function handle in the function [cIn,cEq,gradIn,gradEq] = Constr(x)
cIn = [];
problem structure. To create an anonymous function handle from a function
cEq = sum(x.^2) - 1;
file, use the @ symbol and specify the design variable in parentheses. Then
gradIn = [];
write the function name and the inputs. The same can be done for any
gradEq = 2*x;
nonlinear constraints.
problem.objective = @(x) Obj(x,c) The constraint function is passed as a function handle to the problem
structure.
Every nonlinear constraint can be written in the form f (x) = 0 or f (x) ≤ 0
problem.nonlcon = @(x) Constr(x)
for some nonlinear function f . Multiple constraints can be written in the
same form, with f representing a vector-valued function, with each element
corresponding to the function value of a single constraint.
mathworks.com/training
© 2020 The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc.
See mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may
be trademarks or registered trademarks of their respective holders.