A Short Introduction to Matlab
u Omr UGUR
Institute of Applied Mathematics Middle East Technical University, Ankara, Turkey
March 3, 2011
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
1 / 50
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
2 / 50
Getting Started
Introduction
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
3 / 50
Getting Started
Introduction
Calculator
The simplest way to start with Matlab:
>> (-1+2+3)*4 - 5/6, exp(log(2)), sqrt((-2)^3) ans = 15.1667 ans = 2 ans = 0 + 2.8284i
Matlab has a comprehensive online documentation: help or doc.
>> help elfun, help matfun, ... help sin, help pi, ... help format, help datatypes
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
4 / 50
Getting Started
Introduction
Variables
Built-in functions and constants:
>> i = cos(pi), eps = 10^(-8), sin = 5 i = 0.2837 eps = 1.0000e-08 sin = 5 >> sin(pi) ??? Index exceeds matrix dimensions. >> clear sin
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
5 / 50
Getting Started
Introduction
Variables (cont.)
Variable names in Matlab must start with a letter and may follow by a combination of letters and numbers: Variable 123 Name is valid.
>> clear all >> myVar = 1 + 2*4, -cos(pi); myVar2 = myVar + ans myVar = 9 myVar2 = 10
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
6 / 50
Getting Started
Introduction
Variables (cont.)
>> who Your variables are: ans >> whos Name ans myVar myVar2 myVar myVar2
Size 1x1 1x1 1x1
Bytes 8 8 8
Class double array double array double array
Grand total is 3 elements using 24 bytes
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
7 / 50
Getting Started
Introduction
Saving
It is possible to save all (or some of) workspace variables to a binary le by typing
>> save myFileName myVars
The option -ascii can be used if binary is not desired. The -append option may be used to add variables to an existing le. Matlab also provides a command diary:
>> diary myDiaryFile.txt >> inDiary = 5 inDiary = 5 >> diary off >> notInDiary = 0; >> diary on >> inDiary = 6; >> diary off
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
8 / 50
Getting Started
Matrices and Vectors
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
9 / 50
Getting Started
Matrices and Vectors
Matrices & Vectors
An m n matrix in Matlab is a two-dimensional array of size (m, n).
>> M = [1,2,3; 6,5,4; 7,8,9], col_v = [1;2;3],... row_v = [4,5,6] M = 1 2 3 6 5 4 7 8 9 col_v = 1 2 3 row_v = 4 5 6 >> col_v2 = row_v col_v2 = 4 5 6
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
10 / 50
Getting Started
Matrices and Vectors
Matrices & Vectors (+ and )
>> rand(state, 13); MT = M; A = MT + M; >> b = MT * ( 2*col_v - rand(3,1) ) + 5 b = 66.9998 70.5823 74.1648
The command rand(state, 13) initialises the uniform random number generator, rand, with the seed that is 13. However, randn generates random numbers that are standard normally distributed. The second line above may be rewritten as follows:
>> b = MT * ( 2*eye(3)*col_v - rand(3,1) ) + 5*ones(3,1);
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
11 / 50
Getting Started
Matrices and Vectors
Solving Linear Systems
Linear systems of equations of the form A x = b. Matlab introduces a very useful operator (\), the backslash operator.
>> L = [1 0 0; 2 3 0; 4 5 6]; A = L*L; b = [3 2 1]; >> x = A \ b, r = b - A*x x = 3.9691 -0.2438 -0.1204 r = 1.0e-15 * 0 -0.4441 0
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
12 / 50
Getting Started
Matrices and Vectors
The colon (:) operator
inital:stepsize:final where the default stepsize, which is 1. In this case, inital:final
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
13 / 50
Getting Started
Matrices and Vectors
The colon (:) operator (cont.)
>> randn(state, 13); A = randn(10,15); >> m = 3:8, n = 2:4:15, r = 0:0.25:1 m = 3 4 5 6 7 8 n = 2 6 10 14 r = 0 0.2500 0.5000 0.7500 1.0000 >> B = A(m,n) B = 1.5319 -0.3251 -0.4470 0.1747 -0.1009 -1.9545 0.8423 1.7590 -0.7548 0.0018 1.8984 0.2954 -0.6805 0.1140 1.6201 1.8069 1.1651 -0.9739 2.0801 -0.9937 1.1551 0.7506 -0.0007 0.6790 >> A(4,10), m(2), n(3), B(2,3) ans = 0.8423 ans = 4 ans = 10 ans = 0.8423 >> B(2,:) ans = -0.1009 -1.9545 1.7590 u Omr UGUR (Middle East Technical University) 0.8423 Introduction to Matlab @ IAM @ METU A Short
March 3, 2011
14 / 50
Getting Started
Matrices and Vectors
The colon (:) operator (cont.)
For instance, the following Matlab codes simply changes the jth column of the matrix B.
>> rand(state,13); A = rand(3,5); >> B = zeros(size(A)); j = 3; >> B(:,j) = A(:,5), i = [1 3]; B = 0 0 0.8187 0 0 0 0.4153 0 0 0 0.4270 0 >> B(i,:) = [ 1 2 3 4 5; 6:10 ] B = 1.0000 2.0000 3.0000 4.0000 0 0 0.4153 0 6.0000 7.0000 8.0000 9.0000
0 0 0
5.0000 0 10.0000
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
15 / 50
Getting Started
Matrices and Vectors
Element-wise Computations
Here is an element-by-element operations on matrices:
>> x = linspace(-pi,pi,5), y = x.^2, z = x.*y, y2 = z ./ x x = -3.1416 -1.5708 0 1.5708 3.1416 y = 9.8696 2.4674 0 2.4674 9.8696 z = -31.0063 -3.8758 0 3.8758 31.0063 Warning: Divide by zero. y2 = 9.8696 2.4674 NaN 2.4674 9.8696 >> [1 2; 3 4] .^ [4 3; 2 1] ans = 1 8 9 4
Matlab built-in function linspace(a, b, n): n, is optional and its default value is 100.
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
16 / 50
Getting Started
Matrices and Vectors
Element-wise Computations (cont.)
Many built-in functions, such as sin, cos, exp, log, acts on the entries of the matrices given as input:
>> x = linspace(-pi,pi,5); y = sin(x), z = exp(x) y = -0.0000 -1.0000 0 1.0000 0.0000 z = 0.0432 0.2079 1.0000 4.8105 23.1407 >> t = atan( [x; y; z] ), e = exp( t ) t = -1.2626 -1.0039 0 1.0039 1.2626 -0.0000 -0.7854 0 0.7854 0.0000 0.0432 0.2050 0.7854 1.3658 1.5276 e = 0.2829 0.3665 1.0000 2.7289 3.5347 1.0000 0.4559 1.0000 2.1933 1.0000 1.0441 1.2275 2.1933 3.9190 4.6071
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
17 / 50
Graphics
2-D Plot
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
18 / 50
Graphics
2-D Plot
Plotting
The most common plotting function in Matlab may be the plot: plot(x, y) or plot(x, y, style)
One can combine several drawings in a single plot function as plot(x1, y1, style1, x2, y2, style2, ...)
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
19 / 50
Graphics
2-D Plot
Plotting (cont.)
>> >> >> >> >> >> x1 = linspace(0,2*pi,20); x2 = 0:pi/20:2*pi; y1 = sin(x1); y2 = cos(x2); y3 = exp(-abs(x1-pi)); plot(x1, y1), hold on plot(x2, y2, r+:), plot(x1, y3, -.o) plot([x1; x1], [y1; y3], -.x), hold off print -depsc -r900 -cmyk ../figures/appendixPlot_1
1
0.8
0.6
0.4
0.2
0.2
0.4
0.6
0.8
Figure: Superimposed two-dimensional plots: using plot
u Omr UGUR (Middle East Technical University) A Short Introduction to Matlab @ IAM @ METU March 3, 2011 20 / 50
Graphics
2-D Plot
Plotting: style parameters
Table: Some of the style parameters in plotting graphs
Colours b g r c m y k blue green red cyan magenta yellow black . o x + * s d v
Points point circle x-mark plus star square diamond triangle (down) : -. --
Lines solid dotted dashdot dashed no line
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
21 / 50
Graphics
2-D Plot
Plotting: subplot
>> >> >> >> >> >> >> >> >> x = linspace(0,2*pi); subplot(2,2,1); plot(x, sin(x), x, cos(x), --) xlabel(x), ylabel(y), title(Place (1,1)), grid on subplot(2,2,2); plot(exp(i*x)), title(Place (1,2): z = e^{ix}) axis square, text(0,0, i is complex) subplot(2,2,3); polar(x, ones(size(x))), title(Place (2,1)) subplot(2,2,4); semilogx(x,sin(x), x,cos(x), --) title(Place: (2,2)), grid on legend(sin, cos, Location, SouthWest)
Place (1,1) 1 1 Place (1,2): z = eix
0.5
0.5
i is complex
0.5
0.5
4 x Place (2,1) 90 1 120 60 0.5
1 1
0.5
0.5
Place: (2,2) 1
150
30
0.5
180
210 240 270 300
330
0.5 sin cos 1 2 10 10
1
10
10
Figure: Figure window split into 2 2 sub-windows by using subplot
u Omr UGUR (Middle East Technical University) A Short Introduction to Matlab @ IAM @ METU March 3, 2011 22 / 50
Graphics
3-D Plot
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
23 / 50
Graphics
3-D Plot
3-D Plotting
>> x = linspace(-2,2); y = linspace(-2,2,50); >> [X, Y] = meshgrid(x,y); whos Name Size Bytes Class X Y x y 50x100 50x100 1x100 1x50 40000 40000 800 400 double double double double array array array array
Grand total is 10150 elements using 81200 bytes >> X(1:5, 1:5), Y(1:5, ans = -2.0000 -1.9596 -2.0000 -1.9596 -2.0000 -1.9596 -2.0000 -1.9596 -2.0000 -1.9596 ans = -2.0000 -2.0000 -1.9184 -1.9184 -1.8367 -1.8367 -1.7551 -1.7551 -1.6735 -1.6735 1:5) -1.9192 -1.9192 -1.9192 -1.9192 -1.9192 -2.0000 -1.9184 -1.8367 -1.7551 -1.6735 -1.8788 -1.8788 -1.8788 -1.8788 -1.8788 -2.0000 -1.9184 -1.8367 -1.7551 -1.6735 -1.8384 -1.8384 -1.8384 -1.8384 -1.8384 -2.0000 -1.9184 -1.8367 -1.7551 -1.6735
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
24 / 50
Graphics
3-D Plot
3-D Plotting (cont.)
>> z = X.^2 + Y.^2; whos z Name Size z 50x100 Bytes 40000 Class double array
Grand total is 5000 elements using 40000 bytes >> >> >> >> >> >> >> >> >> >> subplot(2,2,1), mesh(x,y,z), xlabel(x), ylabel(y) zlabel(z), hold on, contour(x,y,z), title(mesh + contour) subplot(2,2,2), surf(x,y,z), xlabel(x), ylabel(y) zlabel(z), shading interp, title(surf + shading) myZ = z .* exp(-z); subplot(2,2,3), contour3(x,y,myZ,20), xlabel(x), ylabel(y) zlabel(myZ), title(contour3) subplot(2,2,4), H = contour(x,y,myZ); xlabel(x), ylabel(y) zlabel(myZ), title(contour + clabel), clabel(H) print -depsc -r300 -cmyk ../figures/appendixPlot_3D
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
25 / 50
Graphics
3-D Plot
3-D Plotting (cont.)
0.05
0.1 0.15 0.2 0.25 0.3 0.35 0.35 0.3 0.25 0.2 0.15 0.1 0.05
0.05
0.05
0.05
Figure: Three-dimensional graphics in Matlab
u Omr UGUR (Middle East Technical University) A Short Introduction to Matlab @ IAM @ METU March 3, 2011 26 / 50
Graphics
3-D Plot
3-D Plotting: plot3
plot3: plots curves (or lines) in three-dimensional space. For example, for [0, 2], r = 2(1 + cos ) denes a cardioid in polar coordinates, where x = r cos , y = r sin .
Now, if we let z = , then we have a parametric curve in 3-dimensional space.
>> >> >> >> >> >> >> t = linspace(0,2*pi); r = 2 * ( 1 + cos(t) ); x = r .* cos(t); y = r .* sin(t); z = t; subplot(1,2,1), plot(x, y, r), xlabel(x), ylabel(y) axis square, grid on, title(cardioid) subplot(1,2,2), plot3(x, y, z), xlabel(x), ylabel(y), hold on axis square, grid on, title(in 3-D), zlabel(z = t) plot3(x, y, zeros(size(x)), r), view(-40, 60)
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
27 / 50
Graphics
3-D Plot
3-D Plotting: plot3 (cont.)
in 3D cardioid 3 2 10 1 z=t 5 0 4 2 0 3 1 0 1 x 2 3 4 y 2 4 1 1 0 x 2 4 3 0 1 2 y
Figure: Parametric curves in two- and three-dimensions
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
28 / 50
Programming in Matlab
Introduction
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
29 / 50
Programming in Matlab
Introduction
Scripts
Now, suppose that the m-le in Fig. 5 is accessible by Matlab: the le has the name myScript.m and contains just a sequence of Matlab commands and functions.
>> edit myScript.m >> myScript ans = 0.0058 >> who Your variables are: ans myMat n myScript.m % This script computes the determinant of % a randomly chosen square matrix n = 10; % chosen dimension of the square matrix myMat = rand(n); % random matrix det(myMat) % no semi-colon (;) at the end, so displays the output
Figure: Simple structure of a Matlab script le
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
30 / 50
Programming in Matlab
Introduction
Functions
A function in Matlab is dened generally by an m-le that begins with a line of the following form: function outArguments = NameOfFunAsYouLike(inArguments)
myFunction.m function [argOut1, argOut2] = NameOfFunAsYouLike(argIn1, argIn2) % This function computes the determinant of % a randomly chosen square matrix % % argIn1 : dimension of the matrix % argIn2 : seed to the random number generator % argOut1 : the determinant of the matrix % argOut2 : the random matrix % % Usage : [myVar1, myVar2] = myFunction(myInput1, myInput2) rand(state, argIn2); % initialise the rand argOut2 = rand(argIn1); % random matrix argOut1 = det(argOut2); % output depends how you call the function
Figure: Simple structure of a Matlab function
u Omr UGUR (Middle East Technical University) A Short Introduction to Matlab @ IAM @ METU March 3, 2011 31 / 50
Programming in Matlab
Introduction
Functions (cont.)
>> clear all >> myFunction(2,13) ans = 0.1341 >> [detA, A] = myFunction(2,13), whos detA = 0.1341 A = 0.8214 0.2119 0.6159 0.3221 Name Size Bytes A ans detA 2x2 1x1 1x1 32 8 8
Class double array double array double array
Grand total is 6 elements using 48 bytes >> detA = myFunction(2,13) detA = 0.1341
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
32 / 50
Programming in Matlab
Introduction
Functions: inline
>> myFun = inline(sin(2*pi*x + theta), x, theta) myFun = Inline function: myFun(x,theta) = sin(2*pi*x + theta) >> myFun(1.5, pi) ans = -4.8986e-16
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
33 / 50
Programming in Matlab
Programming Language
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
34 / 50
Programming in Matlab
Programming Language
General
Matlab provides its programming language that includes looping statements, conditional statements, and relational and logical operators. Moreover, it is also possible to use subroutines or programs, or even, objects written in other programming languages, such as Java, C/C++ or Fortran within Matlab. However, we will restrict ourselves to programming in Matlab and illustrate basic control structures.
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
35 / 50
Programming in Matlab
Programming Language
for loops
The basic syntax is for variable = matrix statements end
myMean.m function myMean = myMean( vector ) % myMean = 0; n = length(vector); for i = 1:n myMean = myMean + vector(i); end myMean = myMean ./ n;
Figure: A simple for loop in Matlab
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
36 / 50
Programming in Matlab
Programming Language
for loops (cont.)
>> clear all >> a = rand(1e7,1); >> tic, myMean(a), toc ans = 0.5000 Elapsed time is 0.074817 seconds. >> tic, mean(a), toc ans = 0.5000 Elapsed time is 0.052202 seconds.
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
37 / 50
Programming in Matlab
Programming Language
while loops
Its basic syntax is while expression statements end Some of the logical operators used in Matlab are shown in Table 2.
Table: Some of the logical operators in Matlab
Operator <, <=, >, >= ==, ~= & | ~
u Omr UGUR (Middle East Technical University)
Meaning less than, less than or equal to, etc. equal to, not equal to logical AND logical OR logical NOT
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
38 / 50
Programming in Matlab
Programming Language
while loops (cont.)
The script le myNewton.m describes two inline functions: myFun and myFunDer: f (x) = x sin(x), and f (x) = 1 + cos(x).
The Newtons root nding algorithm approximately computes the solution of the equation f (x) = 0 around a given point x0 : xn+1 = xn f (xn ) , f (xn ) n = 0, 1, 2, . . .
until some certain convergence criteria, such as, |xn+1 xn | .
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
39 / 50
Programming in Matlab
Programming Language
while loops (cont.)
myNewton.m % calculates a zero of the function around x0 upto a tolerance eps myFun = inline(x - cos(x), x); myFunDer = inline(1 + sin(x), x); x0 = 0; dx = 1; % eps = 1e-8; % if you like. disp( x0 dx); while ( abs(dx) > eps ) dx = -myFun(x0) / myFunDer(x0); x0 = x0 + dx; fprintf(%6.4f \t %12.8e\n, x0, dx); end
Figure: Newtons root nding by using while loop in Matlab
>> myNewton x0 dx 1.0000 1.00000000e+00 0.7504 -2.49636132e-01 0.7391 -1.12509769e-02 0.7391 -2.77575261e-05 0.7391 -1.70123407e-10 0.7391 -0.00000000e+00 >> fzero(myFun, 0) ans = 0.7391
u Omr UGUR (Middle East Technical University) A Short Introduction to Matlab @ IAM @ METU March 3, 2011 40 / 50
Programming in Matlab
Programming Language
if statement
In Matlab, the if statements has the following syntax: if expression1 statements1 elseif expression2 statements2 . . . else statements end
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
41 / 50
Programming in Matlab
Programming Language
if statement (cont.)
myPi.m function myPi = calculatePi(method, nPoints) % calculates approximate value of pi if nargin < 1 myPi = pi; disp([Value of "pi" in Matlab: , num2str(myPi)]); elseif ( nargin < 2 & ~isempty(method) ) disp([You want to calculate "pi" by the method: , num2str(method)]) elseif nargin == 2 myPi = acos(-1); disp([Value of pi = acos(-1): , num2str(myPi)]); else myPi = input(Enter the value of "pi" yourself: ); end
Figure: Simple structure of if conditional statements in Matlab
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
42 / 50
Programming in Matlab
Programming Language
if statement (cont.)
>> myPi(); myPi(Monte Carlo); myPi(MC,1e4); Value of "pi" in Matlab: 3.1416 You want to calculate "pi" by the method: Monte Carlo Value of pi = acos(-1): 3.1416 >> myPi(); Enter the value of "pi" yourself: 3 >> myPi([]); Enter the value of "pi" yourself: 3.14 >> myPi([], 10); Value of pi = acos(-1): 3.1416
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
43 / 50
Programming in Matlab
Programming Language
switch statement
The syntax for switch is switch switch expression case case expression1 statements1 case case expression2 statements2 . . . otherwise statements end
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
44 / 50
Programming in Matlab
Programming Language
switch statement (cont.)
>> optionPrice(Monte Carlo) Method to be used is Monte Carlo >> optionPrice(PDE) Method to be used is "partial differential equation" (PDE) >> optionPrice(let it be exact) Exact Solution optionPrice.m function price = optionPrice(method) % method is a string. switch lower(method) case {monte carlo, quasi-monte carlo, mc, qmc} disp(Method to be used is Monte Carlo) case {binomial, trinomial} disp(Method to be used is a Lattice Method) case pde disp(Method to be used is "partial differential equation" (PDE)) otherwise disp(Exact Soultion) end
Figure: Simple structure of switch conditional statements in Matlab
u Omr UGUR (Middle East Technical University) A Short Introduction to Matlab @ IAM @ METU March 3, 2011 45 / 50
Programming in Matlab
Vectorisation
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
46 / 50
Programming in Matlab
Vectorisation
Avoid using for loops
Matlab is internally optimised for working with matrices and, in particular, vectors. As a general rule, if a sample of code needs to be executed quickly, for loops in Matlab should be avoided where possible.
>> clear all, N = 100000; >> tic, vec = (1:N) .^ 2; toc Elapsed time is 0.002010 seconds. >> tic, for i = 1:N, vec(i) = i^2; end, toc Elapsed time is 0.138471 seconds.
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
47 / 50
Programming in Matlab
Vectorisation
Use Matlab algorithms
testMultiplication.m m = 1000; n = 5000; rand(state, 13); A = rand(m,n); x = rand(n,1); y = zeros(m,1); tic; % usual way for j = 1:n % loop over columns for i = 1:m % loop over rows y(i) = y(i) + A(i,j)*x(j); % multiplication rule for matrices end end toc; % disp(num2str(y)), tic; tic; % in general, may be slightly better: vectorised over columns for i = 1:m y(i) = A(i,:) * x; % dot product % y(i) = dot( A(i,:), x ); % seems to be the worst (why?) end toc; % disp(num2str(y)), tic; tic; % best one y = A*x; % Matlabs way of multiplication toc; % disp(num2str(y))
Figure: Vectorisation in Matlab: speeding up calculations
u Omr UGUR (Middle East Technical University) A Short Introduction to Matlab @ IAM @ METU March 3, 2011 48 / 50
Programming in Matlab
Vectorisation
Use Matlab algorithms (cont.)
>> testMultiplication Elapsed time is 0.072986 seconds. Elapsed time is 0.057435 seconds. Elapsed time is 0.019355 seconds.
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
49 / 50
Programming in Matlab
Vectorisation
Thanks!...
Thanks!...
u Omr UGUR (Middle East Technical University)
A Short Introduction to Matlab @ IAM @ METU
March 3, 2011
50 / 50