Tutorial: Using MATLAB For Mathematical Programming: APS502 - Financial Engineering I
Tutorial: Using MATLAB For Mathematical Programming: APS502 - Financial Engineering I
Programming
APS502 - Financial Engineering I
Dexter Wu
Matrix Construction.
Optimization toolbox in MATLAB@.
LP and QP solver.
Numerical examples in MATLAB@.
Q&A and Exercises
De…nition
A Matrix is a table of numbers, similar to a spreadsheet.
2 3
1 4 7
4 0
A= 2 5 8 5 , B = [2, 1] , C = ,
3
3 6 9
2 3
3 4
3 5 7 4 3 1 3
D=4 5 3 5 , DT = ,E = ,E 1 =
4 3 2 1 1 1 4
7 2
Matlab code:
1 >> A = [1 4 7; 2 5 8; 3 6 9;]
2 >> B = [2 1]; C = [0; 3;];
3 >> D = [3 4; 5 3; 7 2;]; D_trans = D’;
4 >> E = [4 3; 1 1;]; E_inv = inv(E);
Operators Examples
1 2 5 7 1+5 2+7
+, - + =
3 4 6 8 3+6 4+8
1 2 5 7 1 5+2 6 1 7+2 8
=
*, ^ 3 4 6 8 3 5+4 6 3 7+4 8
(matrix multiplication)
1 2 0 5 7 2 1 5 2 7 0 2
. =
.*, .^ 3 4 1 6 8 5 3 6 4 8 1 5
(array multiplication)
A/B = A*inv(B)
n, /
AnB = inv(A)*B (B = I )
A(1:3, 4:6) sub-matrix of A that
:, ’
row from 1 to 3 and column from 4 to 6
Manual Entry
By some standard functions
1 zeros(m,n) creates an (m,n) matrix of zeros;
2 ones(m,n) creates an (m,n) matrix of ones;
3 eye(n) creates the (n,n) identity matrix;
By loops
1 cat(dim, A, B)
2 blkdiag() or diag(v)
3 repmat(), reshape() can simplify the loop
optimization)
matrices e¢ ciently
min f T x
x
s.t. A x b
Aeq x = beq
lb x ub
Syntax:
[x, fval, exit‡ag, output, lambda] = linprog(f, A, b, Aeq, beq, lb, ub,
x0, options)
Linprog takes 6 input variables:
f: Objective coe¢ cient
A, b: Inequality constraints ( )
Aeq, beq: Equality constraints
lb, ub: Variable bounds
x0: Initial guess
options: set parameters (e.g. Algorithm) for the solver
Linprog returns 5 output variables:
x: Optimal Solution
fval: Objective Function Value
exit‡ag: optimal, infeasible, unbounded, etc.
output: information about the algorithm
lambda: dual variables
APS502 (MIE, U of T) using MATLAB @ November 10, 2015 10 / 22
LP example (1)
Solve below LP:
min 2x1 x2 + x3
x
s.t. 2x1 3x2 x3 9
2x1 x2 4
x1 + 3x3 = 6
x1 , x3 0, x2 0
Bond 1 2 3
Price 102 99 98
Coupon 5 3.5 3.5
Maturity year 1 2 3
min 12 x T Qx
x
s.t.µT x R
eT x = 1
(x 0)
If the goal return of portfolio is 5.5%, solve MVO with and without
short selling.