Lecture1 Matlab
Lecture1 Matlab
Lecture1 Matlab
Workshop 1 - Introduction
Download Materials:
http://faculty.haas.berkeley.edu/peliu/
computing
Stefano Corradin
MatLab Workshop 1-2 Peng Liu
What is MatLab?
What is MATLAB ?
MATLAB is a computer program that combines computation and
visualization power that makes it particularly useful for engineers.
MATLAB is an executive program, and a script can be made with
a list of MATLAB commands like other programming language.
MATLAB Stands for MATrix LABoratory.
The system was designed to make matrix computation particularly
easy.
The MATLAB environment allows the user to:
manage variables
import and export data
perform calculations
generate plots
develop and manage files for use with MATLAB.
Stefano Corradin
MatLab Workshop 1-3 Peng Liu
MATLAB Environment
To start MATLAB:
START PROGRAMS
PhD & MFE
Applications
MATLAB 7.1
Stefano Corradin
MatLab Workshop 1-4 Peng Liu
Display Windows
Stefano Corradin
MatLab Workshop 1-5 Peng Liu
Display Windows (con’t…)
Graphic (Figure) Window
Displays plots and graphs
Created in response to graphics commands.
Stefano Corradin
MatLab Workshop 1-6 Peng Liu
Getting Help
type one of following commands in the
command window:
help – lists all the help topic
help topic – provides help for the specified topic
help command – provides help for the specified command
help help – provides information on use of the help command
helpwin – opens a separate help window for navigation
lookfor keyword – Search all M-files for keyword
Google “MATLAB helpdesk”
Go to the online HelpDesk provided by
www.mathworks.com
Stefano Corradin
MatLab Workshop 1-7 Peng Liu
Variables
Variable names:
Must start with a letter
May contain only letters, digits, and the underscore “_”
Matlab is case sensitive, i.e. one & OnE are different variables.
Matlab only recognizes the first 31 characters in a variable name.
Assignment statement:
Variable = number;
Variable = expression;
Example:
>> A = 1234; NOTE: when a semi-
>> a = 1234
colon ”;” is placed at
a=
1234 the end of each
command, the result is
not displayed.
Stefano Corradin
MatLab Workshop 1-8 Peng Liu
Variables (con’t…)
Special variables:
ans : default variable name for the result
pi: π = 3.1415926…………
eps: ∈ = 2.2204e-016, smallest amount by which 2 numbers can differ.
Inf or inf : ∞, infinity
NaN or nan: not-a-number
Commands involving variables:
who: lists the names of defined variables
whos: lists the names and sizes of defined variables
clear: clears all varialbes, reset the default values of special
variables.
clear name: clears the variable name
clc: clears the command window
clf: clears the current figure and the graph window.
Stefano Corradin
MatLab Workshop 1-9 Peng Liu
Vectors, Matrices and Linear Algebra
Vectors
Array Operations
Matrices
Solutions to Systems of Linear Equations.
Stefano Corradin
MatLab Workshop 1-10 Peng Liu
Vectors
A row vector in MATLAB can be created by an explicit list, starting with a left bracket,
entering the values separated by spaces (or commas) and closing the vector with a right
bracket.
A column vector can be created the same way, and the rows are separated by semicolons.
To input a matrix, you basically define a variable. For a matrix the form is:
Stefano Corradin
MatLab Workshop 1-11 Peng Liu
Vectors (con’t…)
y = x’ transpose of vector x
dot (x, y) returns the scalar dot product of the vector x and y.
Stefano Corradin
MatLab Workshop 1-13 Peng Liu
Array Operations
Scalar-Array Mathematics
Example:
>> f = [ 1 2; 3 4]
f=
1 2
3 4 Each element in the array f is
>> g = 2*f – 1 multiplied by 2, then
g= subtracted by 1.
1 3
5 7
Stefano Corradin
MatLab Workshop 1-14 Peng Liu
Array Operations (con’t…)
Element-by-Element Array-Array Mathematics.
Example:
>> x = [ 1 2 3 ];
>> y = [ 4 5 6 ];
Each element in x is
>> z = x .* y multiplied by the
z=
4 10 18
corresponding element in y.
Stefano Corradin
MatLab Workshop 1-15 Peng Liu
Matrices
A Matrix array is two-dimensional, having both multiple rows and multiple columns,
similar to vector arrays:
it begins with [, and end with ]
spaces or commas are used to separate elements in a row
semicolon or enter is used to separate rows.
A is an m x n matrix.
•Example:
>> f = [ 1 2 3; 4 5 6]
f=
1 2 3
4 5 6
>> h = [ 2 4 6
1 3 5]
h=
2 4 6
the main 1 3 5
diagonal
Stefano Corradin
MatLab Workshop 1-16 Peng Liu
Matrices (con’t…)
Matrix Addressing:
-- matrixname(row, column)
-- colon may be used in place of a row or column reference to select
the entire row or column.
Example:
recall:
>> f(2,3) f=
ans = 1 2 3
6 4 5 6
>> h(:,1) h=
ans = 2 4 6
1 3 5
2
1
Stefano Corradin
MatLab Workshop 1-17 Peng Liu
Matrices (con’t…)
Some useful
commands:
zeros(n) returns a n x n matrix of zeros
zeros(m,n) returns a m x n matrix of zeros
Stefano Corradin
MatLab Workshop 1-18 Peng Liu
Matrices (con’t…)
more
Transpose Bcommands
= A’
Identity Matrix eye(n) returns an n x n identity matrix
eye(m,n) returns an m x n matrix with ones on the main
diagonal and zeros elsewhere.
Addition and subtraction C=A+B
C=A–B
Scalar Multiplication B = αA, where α is a scalar.
Matrix Multiplication C = A*B
Matrix Inverse B = inv(A), A must be a square matrix in this case.
rank (A) returns the rank of the matrix A.
Matrix Powers B = A.^2 squares each element in the matrix
C = A * A computes A*A, and A must be a square matrix.
Determinant det (A), and A must be a square matrix.
A, B, C are matrices, and m, n, α are
scalars.
Stefano Corradin
MatLab Workshop 1-19 Peng Liu
Solutions to Systems of Linear Equations
Example: a system of 3 linear equations with 3 unknowns (x1, x2, x3):
3x1 + 2x2 – x3 = 10
-x1 + 3x2 + 2x3 = 5
x1 – x2 – x3 = -1
Let :
3 2 − 1 x1 10
A = − 1 3 2 x = x2 b= 5
1 − 1 − 1
x3 − 1
Ax = b
Stefano Corradin
MatLab Workshop 1-20 Peng Liu
Solutions to Systems of Linear Equations
(con’t…)
Solution by Matrix Inverse: Solution by Matrix Division:
Ax = b The solution to the equation
A-1Ax = A-1b Ax = b
x = A-1b can be computed using left division.
MATLAB: MATLAB:
>> A = [ 3 2 -1; -1 3 2; 1 -1 -1]; >> A = [ 3 2 -1; -1 3 2; 1 -1 -1];
>> b = [ 10; 5; -1]; >> b = [ 10; 5; -1];
>> x = inv(A)*b >> x = A\b
x= x=
-2.0000 -2.0000
5.0000 5.0000
-6.0000 -6.0000
Answer: Answer:
x1 = -2, x2 = 5, x3 = -6 x1 = -2, x2 = 5, x3 = -6
NOTE:
left division: A\b b ÷ A right division: x/y x ÷ y
Stefano Corradin
MatLab Workshop 1-21 Peng Liu
Plotting in Matlab
Goal:plot y = sin(x)
Matlab code
xplot = (0 : 0.01 : 2)*pi;
yplot = sin(xplot);
plot(xplot, yplot)
Stefano Corradin
MatLab Workshop 1-22 Peng Liu
Plotting in Matlab (cont.)
1
0.8
0.6
0.4
0.2
0.2
0.4
0.6
0.8
1
0 1 2 3 4 5 6 7
Stefano Corradin
MatLab Workshop 1-23 Peng Liu
Plotting points
xpts = (0 : 0.1 : 2)*pi; % 21 evenly spaced points
ypts = sin(xpts);
1
plot(xpts, ypts, '+')
0.8
0.6
0.4
0.2
0.2
0.4
Type help plot to see 0.6
point specification options 0.8
in addition to '+' 1
0 1 2 3 4 5 6 7
Stefano Corradin
MatLab Workshop 1-24 Peng Liu
Plotting more than one thing
Option 1: inside one plot command
plot(xplot, yplot, xpts, ypts, 'o')
1
0.8
0.6
0.4
0.2
0.2
0.4
0.6
0.8
1
0 1 2 3 4 5 6 7
Stefano Corradin
MatLab Workshop 1-25 Peng Liu
Plotting more than one thing
0.6
0.4
hold on 0
1
0 1 2 3 4 5 6 7
Stefano Corradin
MatLab Workshop 1-26 Peng Liu
Adding color to plots
clf
xplot = (0 : 0.01 : 2)*pi;
yplot = sin(xplot);
hold on
plot(xplot, yplot, 'r') % y = sin(x), red line
plot(xpts, ypts, 'ko') % y = sin(x), black circles
plot(xplot, yplot2, 'g') % y = cos(2x), green line
hold off
Type help plot to see color options
Stefano Corradin
MatLab Workshop 1-27 Peng Liu
Plotting (con’t…)
Plotting Curves:
plot (x,y) – generates a linear plot of the values of x (horizontal axis) and y (vertical axis).
semilogx (x,y) – generate a plot of the values of x and y using a logarithmic scale for x and a
linear scale for y
semilogy (x,y) – generate a plot of the values of x and y using a linear scale for x and a
logarithmic scale for y.
loglog(x,y) – generate a plot of the values of x and y using logarithmic scales for both x and y
Multiple Curves:
plot (x, y, w, z) – multiple curves can be plotted on the same graph by using multiple arguments
in a plot command. The variables x, y, w, and z are vectors. Two curves will be plotted: y vs. x,
and z vs. w.
legend (‘string1’, ‘string2’,…) – used to distinguish between plots on the same graph
exercise: type help legend to learn more on this command.
Multiple Figures:
figure (n) – used in creation of multiple plot windows. place this command before the plot()
command, and the corresponding figure will be labeled as “Figure n”
close – closes the figure n window.
close all – closes all the figure windows.
Subplots:
subplot (m, n, p) – m by n grid of windows, with p specifying the current plot as the
pth window
Stefano Corradin
MatLab Workshop 1-28 Peng Liu
Plotting (con’t…)
Example: (polynomial function)
plot the polynomial using linear/linear scale, log/linear scale, linear/log scale, & log/log scale:
y = 2x2 + 7x + 9
Stefano Corradin
MatLab Workshop 1-29 Peng Liu
Plotting (con’t…)
Stefano Corradin
MatLab Workshop 1-30 Peng Liu
Plotting (con’t…)
Adding new curves to the existing graph:
Use the hold command to add lines/points to an existing plot.
hold on – retain existing axes, add new curves to current axes. Axes are
rescaled when necessary.
hold off – release the current figure window for new plots
Grids and
Labels:
Command Description
text (x,y,’text’) Adds text in quotes to location (x,y) on the current axes, where (x,y) is in units
from the current plot.
Stefano Corradin
MatLab Workshop 1-31 Peng Liu
Additional commands for plotting
color of the point or curve Marker of the data Plot line styles
points
Symbol Marker
Symbol Line Style
Symbol Color . •
– solid line
y yellow
o °
m magenta : dotted line
x ×
c cyan –. dash-dot line
r red + +
–– dashed line
g green * ∗
b blue s □
w white
d ◊
k black
v ∇
^ ∆
h hexagram
Stefano Corradin
MatLab Workshop 1-32 Peng Liu
Flow control - selection
The if-elseif-else construction
if <logical expression>
<commands>
elseif <logical expression>
<commands>
else
<commands>
end
Stefano Corradin
MatLab Workshop 1-33 Peng Liu
Logical expressions (try help)
Relational operators (compare arrays of same sizes)
== (equal to) ~= (not equal)
< (less than) <= (less than or equal to)
> (greater than) >= (greater than or equal to)
Logical functions
xor
isempty
any
all
Stefano Corradin
MatLab Workshop 1-34 Peng Liu
M-Files
So far, we have executed the commands in the command
window. But a more practical way is to create a M-file.
The M-file is a text file that consists a group of
MATLAB commands.
MATLAB can open and execute the commands
exactly as if they were entered at the MATLAB
command window.
To run the M-files, just type the file name in the
command window. (make sure the current
working directory is set correctly)
Stefano Corradin
MatLab Workshop 1-35 Peng Liu
Scripts or function: when use what?
Functions
Take inputs, generate outputs, have internal
variables
Solve general problem for arbitrary parameters
Scripts
Operate on global workspace
Document work, design experiment or test
Stefano Corradin
MatLab Workshop 1-36 Peng Liu
User-Defined Function
Add the following command in the beginning of your m-file:
function [output variables] = function_name (input variables);
Stefano Corradin
MatLab Workshop 1-39 Peng Liu
Flow control – conditional repetition
while-loops
while <logical expression>
<statements>
End
<statements> are executed repeatedly as long as
the <logical expression> evaluates to true
Stefano Corradin
MatLab Workshop 1-40 Peng Liu
Flow control – conditional repetition
Solutions to nonlinear equations
Stefano Corradin
MatLab Workshop 1-41 Peng Liu
Flow control – conditional repetition
newton.m
function [x,n] = newton(x0,tol,maxit)
% NEWTON – Newton’s method for solving equations
% [x,n] = NEWTON(x0,tol,maxit)
x = x0; n = 0; done=0;
while ~done,
n = n + 1;
x_new = x - (exp(-x)-sin(x))/(-exp(-x)-cos(x));
done=(n>=maxit) | ( abs(x_new-x)<tol );
x=x_new;
end
>> [x,n]=newton(0,eps,10)
Stefano Corradin
MatLab Workshop 1-42 Peng Liu
Black Vol using Newton Method
Result:
x=
0.5885
n=
6
Question:code a function that produce Black-
Scholes Volatility from Option prices!!
Stefano Corradin
MatLab Workshop 1-43 Peng Liu
Function functions
Do we need to re-write newton.m for every new
function?
No! General purpose functions take other m-files
as input.
>> help feval
>> [f,f_prime]=feval(’myfun’,0);
myfun.m
function [f,f_prime] = myfun(x)
% MYFUN– Evaluate f(x) = exp(x)-sin(x)
% and its first derivative
% [f,f_prime] = myfun(x)
f=exp(-x)-sin(x);
f_prime=-exp(-x)-cos(x);
Stefano Corradin
MatLab Workshop 1-44 Peng Liu
Function functions
Can update newton.m newtonf.m
function [x,n] = newtonf(fname,x0,tol,maxit)
% NEWTON – Newton’s method for solving equations
% [x,n] = NEWTON(fname,x0,tol,maxit)
x = x0; n = 0; done=0;
while ~done,
n = n + 1;
[f,f_prime]=feval(fname,x);
dx
x_new = x – f/f_prime;
= f ( x, t )
done=(n>maxit) | (dtabs(x_new-x)<tol );
x=x_new;
end
>> [x,n]=newtonf(’myfun’,0,1e-3,10)
Stefano Corradin
MatLab Workshop 1-45 Peng Liu
Example: Pricing options in CRR
Binomial Tree
Open P:\PodiumPC\2006MFE
Double Click CRR.m
It will open an editor window beginning with
function [] = CRR(CallPut, AssetP, Strike, RiskFree, Div, Time, Vol, nSteps)
% Computes the Cox, Ross & Rubinstein (1979) Binomial Tree for European
%Call/Put Option Values based on the following inputs:
% CallPut = Call = 1, Put = 0
% AssetP = Underlying Asset Price
% Strike = Strike Price of Option
% RiskFree = Risk Free rate of interest annualized eg. 0.05
% Div = Dividend Yield of Underlying
% Time = Time to Maturity in years
% Vol = Volatility of the Underlying
% nSteps = Number of Time Steps for Binomial Tree to take
Stefano Corradin
MatLab Workshop 1-46 Peng Liu
Example: Pricing options in CRR
Binomial Tree (cont.)
dt = Time / nSteps;
if CallPut
b = 1;
end
if ~CallPut
b = -1;
end
RR = exp(RiskFree * dt);
Up = exp(Vol * sqrt(dt));
Down = 1 / Up;
Q_up = (exp((RiskFree - Div) * dt) - Down) / (Up - Down);
Q_down = 1 - Q_up;
Df = exp(-RiskFree * dt); %Df: Discount Factor
Stefano Corradin
MatLab Workshop 1-47 Peng Liu
Example: Pricing options in CRR
Binomial Tree (cont.)
%Populate all possible stock prices and option values on the end notes of the tree
for i = 0:nSteps
state = i + 1;
St = AssetP * Up ^ i * Down ^ (nSteps - i);
Value(state) = max(0, b * (St - Strike));
End
for k = nSteps - 1 : -1 : 0
for i = 0:k
state = i + 1;
Value(state) = (Q_up * Value(state + 1) + Q_down * Value(state)) * Df;
end
end
Binomial = Value(1)
Stefano Corradin
MatLab Workshop 1-48 Peng Liu
Results
Stefano Corradin
MatLab Workshop 1-49 Peng Liu
Results
Stefano Corradin
MatLab Workshop 1-50 Peng Liu
Results
Stefano Corradin
MatLab Workshop 1-51 Peng Liu
Results
Stefano Corradin
MatLab Workshop 1-52 Peng Liu
Example: Pricing options in CRR
Binomial Tree (cont.)
>> CRR(1,100,105,0.05,0,2,0.4,100)
Binomial =
24.3440
>> CRR(0,100,105,0.05,0,2,0.4,100)
Binomial =
19.3520
Stefano Corradin
MatLab Workshop 1-53 Peng Liu
Results
Stefano Corradin
MatLab Workshop 1-54 Peng Liu
How to Leave Matlab?
The answer to the most popular question
concerning any program is this: leave a
Matlab session
Leave Matlab by typing
quit
or by typing
exit
To the Matlab prompt.
Stefano Corradin
MatLab Workshop 1-55 Peng Liu