Tutorial 3 Matlab Sept07

Embed Size (px)

Citation preview

  • 7/27/2019 Tutorial 3 Matlab Sept07

    1/19

    SEAS Short Course on MATLAB

    Tutorial 3: Plots & Other Functions

    Peter J. Ramadge & Ronnie Sircar12 September, 2007

    1 Summary

    This tutorial is a set example applications intended to enrich the material from the previoustutorials. The following new commands and structures are discussed:

    linspace - sets up vectors of equally spaced points between given limits. figure, clf - selecting and clearing the active figure window LineWidth - controls the line width in plotting axis - controls axis properties text - places text on graphs legend places a legend on a plot. hold on and hold off - control overwriting of plots

    subplot - used for creating arrays of plots. mesh, contour - 3-D mesh and contour plots quiver - quiver plots of 2-D vector fields imagesc, colorbar, colormap - displaying matrices as images. strings and string indexing. cell arrays of strings.

    sprintf - converts numerical values to a formatted string representation. eval - evaluation of a string as a MATLAB expression. ode45 - numerically find the solution of an o.d.e. randn - generate a random number drawn from a normal distribution.

    1

  • 7/27/2019 Tutorial 3 Matlab Sept07

    2/19

    2 More Complex 2-D Plots

    2.1 Plotting a trajectory of the logistic map

    We will explore additional aspects of 2-D curve plotting by investigating the famous logisticmap:

    xk = a(1 xk1)xk1.It arises in the study of population dynamics where it provided one of the first simple examplesof chaotic behavior from a deterministic equation, as we shall see.

    Defining the function f(x) = a(1 x)x, we generate a sequence of scalar values by theiteration xk = f(xk1), k = 0, 1, 2, . . . . The first value, x0, is called the initial condition andthe entire sequence is called the trajectory starting from x0. The value a is a fixed but selectableparameter. We assume that 0 a 4 and that x0 [0, 1]. In this case, f maps the unitinterval into itself and the trajectory remains in [0, 1] for all k 0.

    The logistic function f can be coded as a simple function M-file taking two parameters andreturning one value (for brevity we omit the usual program comments):

    function y=logistic(x,a)

    y=a*(1-x).*x;

    Notice that we have allowed for the possibility that x and y are vectors but have assumed thata is a scalar.

    We can plot a trajectory of the logistic equation with the following MATLAB function.

    function tx=plottraj(a,x0,NI,fig)

    % a is scalar parameter

    % xO is scalar initial condition% NI is number of iterations

    % fig is figure number

    tx=zeros(1,NI);

    tx(1)=x0; % first element of tx is the initial value

    for j=2:1:NI

    tx(j)=logistic(tx(j-1),a); % iterate the logistic function

    end

    figure(fig); clf; lw=1.5;

    plot(tx,--r.,LineWidth,lw) % plot as red dots joined by dotted line

    grid; axis([1 NI 0 1]);xlabel(Iteration number k); ylabel(x_k)

    text(15,0.275,sprintf(a = %4.2f,ap));

    text(15,0.225,sprintf(x_0 = %4.2f,x0));

    There are a several new commands introduced in this function:

    The command figure(n), where n is an integer, makes figure window n the active figurewindow.

    2

  • 7/27/2019 Tutorial 3 Matlab Sept07

    3/19

    5 10 15 20 25 30 35 40 45 500

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    0.8

    0.9

    1

    iteration number k

    xk

    a = 2.5

    x0

    = 0.7

    5 10 15 20 25 30 35 40 45 500

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    0.8

    0.9

    1

    iteration number k

    xk

    a = 3.25

    x0

    = 0.7

    5 10 15 20 25 30 35 40 45 500

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    0.8

    0.9

    1

    iteration number k

    xk

    a = 3.5

    x0

    = 0.7

    10 20 30 40 50 60 70 80 90 1000

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    0.8

    0.9

    1

    iteration number k

    xk

    a = 3.8

    x0

    = 0.7

    Figure 1: Trajectories of the logistic equation.

    The command clf clears the current figure window. Before you begin a new plot, it is agood practice to clear the window.

    The LineWidth parameter controls the thickness of the line used in plotting. It can beset within the plot command as indicated.

    The axis command controls many aspects of the plot axis. Here we have used it tomanually set the upper and lower limits of the x and y axes. The syntax for this isaxis([xmin xmax ymin ymax]).

    The function sprintf converts numerical values into a formatted string representation.This is very useful for recording the values of variables on plots.

    The text command places text on a graph. Here it is used to indicate the values of a

    3

  • 7/27/2019 Tutorial 3 Matlab Sept07

    4/19

    and the initial condition x0. The syntax is text(xpos, ypos, textstring).

    This function was used to produce the example graphs shown in Figure 1. For the top lefttrajectory, a = 2.5 and the trajectory settles into the final value x = 0.6. As we increase

    the value of a, however, the behavior of the trajectory changes. For example, when a = 3.25,the top right trajectory settles into a periodic pattern alternating between two values. This iscalled a periodic orbit with period 2. As a increases still further the character of the trajectorychanges again. For a = 3.5, the trajectory from x0 = 0.7 now settles into a periodic orbit withperiod 4. Finally, for a = 3.8 the trajectory appears chaotic in that it does not settle into anydiscernable repeating pattern. You can try different values of a and x0 yourself and examinethe resulting trajectories.

    2.2 Multiple curves on a single plot

    The fixed points of the logistic equation are the solutions of the equation f(x) = x. Theseoccur at intersections of the curve y = f(x) with the line y = x. For a > 1, the only solutionsare 0 and x = a 1/a.

    Periodic orbits can be found in a similar fashion. For a period 2 orbit, f(x1) = x2 andf(x2) = x1. Thus f(f(x1)) = x1 and f(f(x2)) = x2, i.e., x1 and x2 are fixed points of thecomposition f2() = f(f()). Notice that the fixed points of f are always fixed points of f2. Soperiod 2 orbits are the fixed points of f2 that are not fixed points of f1 = f.

    0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    0.8

    0.9

    1

    x

    fk

    (x)

    a = [3.5]

    y=x

    f1

    f2

    0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    0.8

    0.9

    1

    x

    fk

    (x)

    a = [2.8 3 3.2 3.4]

    y=x

    f1

    f2

    Figure 2: The logistic equation f and its composition f2.

    The fixed points off and f2 occur at the intersections of the curves y = f(x) and y = f2(x)with the line y = x. Hence we can display them by plotting f(x), f2(x) and the line y = x onthe same graph. Here is a MATLAB function that will do the job:

    function y=plotf(a,N,fig)

    4

  • 7/27/2019 Tutorial 3 Matlab Sept07

    5/19

    % a is vector of parameter values

    % N is number of samples of x

    % fig is figure number

    x=linspace(0,1,N);M=length(a);

    kmax=5;

    figure(fig)

    clf

    lw=1.5;

    plot([0 1],[0,1],--k,LineWidth,lw) % plot the line y=x in black dashes

    grid; axis([0 1 0 1]);

    xlabel(x)

    ylabel(f_k(x));

    text(0.15,0.95,sprintf(a = %4.2f,a))axis(square);

    myc=rbkgmc;

    hold on % hold on => new plots added to existing plot

    for j=1:1:M

    y=x;

    for k=1:kmax

    y=logistic(y,a(j));

    plot(x,y,[myc(k) -],LineWidth,lw);

    end

    endhold off % hold off when done

    legend(y=x,f_1,f_2,Location,south);

    There are three new commands and a useful construct introduced in this code:

    The command hold on allows a plot command to draw over an existing plot without firsterasing what is already there. The command hold off turns off this feature.

    linspace sets up a row vector of equally spaced points between given upper and lowerlimits. The syntax is linspace(xmin,xmax,N) where xmin and xmax are the limits andN is the number of points.

    We have used the axis command three times: to set the upper and lower limits on thex and y axes, to make the scales on the two axes equal, and to force the aspect ratio ofthe plot to be 1:1, i.e., a square.

    The command legend places a legend on the plot. See help legend for full disclosure. A string myc=rbkgmc with six entries is defined. The entries can be indexed as myc(1),

    myc(2), etc. This used in the plot command within the loop to make the line color a

    5

  • 7/27/2019 Tutorial 3 Matlab Sept07

    6/19

    function of the loop variable k. We have constructed a text string as the concatenation ofthe string returned by myc(k) and the string -. To do this we simply make the stringsthe entries of a row vector.

    The graph shown on the left in Figure 2 results when the function is called with a=3.5.The graph on the right is the result with a=[2.8:0.2:3.4]. For a < 3 the graph of f2 onlyintersects the line x = y at the fixed point x. However, for a > 3 there are three intersectionsof f2 with the line: one at x, one above x and one below x. The points above and below x

    are not fixed points of f but they are fixed points of f2. Hence they form a nontrivial periodicorbit of period 2.

    0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

    0.2

    0.4

    0.6

    0.8

    1

    x

    fk

    (x)

    a = [3.55]

    y=x f1f2

    f3

    f4

    f5

    Figure 3: Compositions 1 through 5 of the logistic equation.

    It is simple matter to add plots of higher order compositions of f to the graph and henceto determine visually if there are period 3, 4, etc., orbits. The plot in Figure 3 shows the resultfor periods 1 through 5 with a = 3.55. How many periodic orbits does the graph indicateand what are the periods? Notice the aspect ratio of the plot. We replaced the commandaxis(square) with the command pbaspect([2.5 1 1]). This changes the aspect ratio ofthe plot box to 2.5(x) : 1(y). The third number is for a z axis. You can experiment with the

    program and plot your own version of this graph. To show the plot lines sequentially you canmodify the inner loop as follows:

    for k=1:kmax

    y=logistic(y,a(j));

    plot(x,y,[c(k) -],LineWidth,lw);

    pause

    end

    6

  • 7/27/2019 Tutorial 3 Matlab Sept07

    7/19

    The command pause, without any argument, causes MATLAB to wait for the user to pressany key.

    Another useful tool is subplot. The command subplot(M,N,k) tells MATLAB that wewant to plot several plots on the same figure with the plots arranged in a rectangular grid of

    size M by N and that at the moment you want to work on subplot k. The subplots are indexedby a single integer k by counting along the rows from top to bottom. So if M=2 and N=3, thenk=3 is the third subplot on the first row, k=5 is the second subplot on the second row, and soon. The command can be called, for example, as follows:

    for k=1:M*N

    ... commands that define x and y

    subplot(M,N,k), plot(x,y,r--)

    end

    3 3-D Plots Scalar functions of two variables: Real valued functions of the form f(x, y), where

    x and y are real valued, arise in many engineering applications. For example, f mightbe the displacement of a vibrating plate at location (x, y), or the intensity of an analogimage at position (x, y), or the temperature of a 2-D surface at location (x, y), and so on.

    Working example: As a simple working example we consider the sum of two 2-DGaussian density functions:

    f(x, y) = e1

    2(x2+y2) + e

    1

    2((x2)2+(y2)2)

    Representing a 2-D function in MATLAB: To represent a 2-D function in MATLABwe must restrict the range of values of x and y to finite intervals and sample the valuesof the function over this range at a finite number of points. Assume we restrict attentionto the rectangle: xmin x xmax and ymin y ymax. A simple way to sample x andy is to fix integers N and M and set:

    x=linspace(xmin,xmax,N);

    y=linspace(ymin,ymax,M);

    This results in N sample points in x and M in y.

    Our sample points define a rectangular grid with the (j, k)th sample point at (xj, yk), for

    j = 1, . . . , N and k = 1, . . . , M . The samples of the function f will form a matrix with(j, k)th entry f(xj, yk), j = 1, . . . , N , k = 1, . . . , M .

    To take advantage of MATLABs convention of applying scalar functions to an array, weneed to represent the sample values of x and y as matrices. We do this by replicating therow vector x M times (one for each value in y) to form a matrix X. Each column of X hasthe same value in each entry - for column j this is the value xj. We do the same thing toform a matrix Y except that each column of Y is a replicate of the column vector y. Asimple example:

    7

  • 7/27/2019 Tutorial 3 Matlab Sept07

    8/19

  • 7/27/2019 Tutorial 3 Matlab Sept07

    9/19

  • 7/27/2019 Tutorial 3 Matlab Sept07

    10/19

    4

    2

    0

    2

    4

    4

    2

    0

    2

    4

    0

    0.2

    0.4

    0.6

    0.8

    1

    1.2

    1.4

    xy

    f

    x

    y

    3 2 1 0 1 2 3 44

    3

    2

    1

    0

    1

    2

    3

    4

    Figure 4: A mesh and contour plot of the function f(x, y).

    3.1 Image Plots

    You need to have a color printout of this document, or view the document on your computerscreen to fully appreciate the images in this section.

    Displaying a matrix as an image: A matrix A is a rectangular array of numbers. Thisarray can be displayed as an image by representing each number as a color or gray level.To do so, MATLAB makes use of color map.

    Color maps: A color map is an N 3 array of numbers each between 0 and 1. The firstcolumn of the color map represents a fraction of red, the second of green and the third ofblue. So (1, 0, 0) represents pure red; (1, 1, 1) is white; (0, 0, 0) is black; and (0.5, 0.5, 0.5) ismid gray. The number of rows in the color map is the number of colors used to representnumerical values. The idea is that each number in the interval [0, 1] is mapped in anorder preserving way to a row of the color map and the color coded by that row is usedto represent the number in an image. MATLAB has several predefined color maps eachwith 256 rows. Some of them are displayed as images in Figure 5. The first row (top ofthe figure) represents the number 1 and the last row represents 0. The default color mapis jet. You can change to a new color map with the command colormap(mapname).

    imagesc: If X is a matrix, the function imagesc(X) scales the values of X to the range[0, 1] and then displays the matrix as an image using the current color map. Example: The following commands display the matrix F (computed when we did the

    mesh and contour plots of the function f) as an image with the jet colormap.

    figure(4); clf

    colormap(jet);

    imagesc(F); colorbar;

    10

  • 7/27/2019 Tutorial 3 Matlab Sept07

    11/19

    jet0.5 1 1.5

    50

    100

    150

    200

    250

    hot0.5 1 1.5

    50

    100

    150

    200

    250

    cool0.5 1 1.5

    50

    100

    150

    200

    250

    copper0.5 1 1.5

    50

    100

    150

    200

    250

    gray0.5 1 1.5

    50

    100

    150

    200

    250

    Figure 5: Some standard MATLAB color maps.

    The resultant image is show on the left of Figure 6. The image on the right is the sameexcept displayed with the copper color map.

    x

    y

    5 10 15 20 25 30 35 40 45 50

    5

    10

    15

    20

    25

    30

    35

    40

    45

    50

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    0.8

    0.9

    1

    x

    y

    5 10 15 20 25 30 35 40 45 50

    5

    10

    15

    20

    25

    30

    35

    40

    45

    50

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    0.8

    0.9

    1

    Figure 6: The samples of the function f displayed as an image.

    Example (More complex): The image in Figure 5 was produced by the following code.

    % Color bar script

    % written by pjr 8/30/05

    clear all

    figure(1);clf

    cmaps={jet hot cool copper gray};

    11

  • 7/27/2019 Tutorial 3 Matlab Sept07

    12/19

    m=length(cmaps);

    M=1; N=m;

    for k=1:m

    subplot(M,N,k)

    map=eval(cmaps{k});Im(:,1,1:3)=map(end:-1:1,1:3);

    image(Im)

    xlabel(cmaps{k})

    end

    This script is a little more complicated than other examples we have seen and contains anumber of new commands. We will go through them one at a time.

    MATLAB represents a string as an array of characters. So if s=Go Tigers, then

    s(1) is G, s(2) is o, s(6) is g and so on. If two strings have the same length,then we can store them as the rows of a matrix:

    S(1,:)=Go Tigers;

    S(2,:)=Princeton;

    Then S(1,:) returns the string Go Tigers, S(2,:) returns the string Princetonand S(1,4:end) returns Tigers. However, if the strings have different lengths,they cannot be stored directly in a matrix without first padding the shorter stringswith spaces so that all strings have the same length. This can be done with thechar command. However, a simpler way is to use a cell array of strings. Thecommand cmaps=

    {jet hot cool copper gray

    }defines a cell array of

    strings. The delimiters { and } enclose the strings included in the array. Theelements of the cell array can be referenced using braces { }: cmaps{1} is the stringjet, cmaps{3} is the string cool, and so on.

    The function eval evaluates a string as if it were an MATLAB expression. In ourcase, the string is the kth string in cmaps. This is the name of a MATLAB color map,i.e. a MATLAB variable, so eval returns the value of that variable. The variable

    map is thus the 256 3 color map indicated by the name stored in cmapsk. The command Im(:,1,1:3)=map(end:-1:1,1:3); forms an RGB image with 256

    rows and 1 column. The color planes of the RGB image are just the columns of thecolor map map.

    IfX is an p q 3 array of real numbers in the the range [0, 1], the command imageinterprets the matrix X(:,:,k) as the R (k = 1), G (k = 2) and B (k = 3) valuesof an image and display the image on the screen. This is probably more than youneeded to know at this point. Dont worry if this seems a little complicated. Its anadvanced example.

    12

  • 7/27/2019 Tutorial 3 Matlab Sept07

    13/19

    4 3 2 1 0 1 2 3 44

    3

    2

    1

    0

    1

    2

    3

    4

    x

    y

    x

    y

    4 3 2 1 0 1 2 3 44

    3

    2

    1

    0

    1

    2

    3

    4

    Figure 7: A quiver plot of the gradient of the function f(x, y).

    4 Vector Fields and Quiver Plots

    Gradient: Let fx = f/x and fy = f/y denote the partial derivatives of thefunction f(x, y) with respect to x and y. The gradient off(x, y) is the vector of partialderivatives

    f(x, y) =

    fx(x, y)fy(x, y)

    At each point (x, y), the gradient vector points in the direction of steepest increase ofthe function f at that point and its magnitude is a measure of how rapidly the functionis changing in that direction. The negative of the gradient points in the direction ofsteepest decrease of the function. Hence a simple method for finding a (local) minimumof a function is to take small steps in the direction of the negative gradient, a methodappropriately known as steepest descent.

    The gradient is an example of a 2-D vector field: a function that associates with eachpoint (x, y) of the plane a vector v(x, y) = (v1(x, y), v2(x, y))

    T R2. Quiver Plots: We can visualize a vector field with a MATLAB quiver plot. The vec-

    tor field has two components: v1(x, y) and v2(x, y); each component is a scalar valued

    function of (x, y). Hence we can compute each component as discussed in the previ-ous section. Then we can display the vector field on a quiver plot with the commandquiver(X,Y,V1,V2). This plots v(x, y) as a small arrow from the point (x, y) pointingin the direction of v with length proportional to the norm of v.

    The gradient of our working example function f(x, y) is:

    f(x, y) =xe12 (x2+y2) (x 2)e12 ((x2)2+(y2)2)

    ye12 (x2+y2) (y 2)e12 ((x2)2+(y2)2)

    13

  • 7/27/2019 Tutorial 3 Matlab Sept07

    14/19

    We can display this as a quiver plot by adding the following additional commands to ourprevious script that plotted f:

    figure(3); clf

    Fx=-X.*F0-(X-2).*F1;Fy=-Y.*F0-(Y-2).*F1;

    quiver(X,Y,Fx,Fy)

    where X, Y, F0, F1 were defined and computed in the script to plot f. The result isshown on the left in Figure 7. By using hold on and hold off we can combine a contourplot of f with the quiver plot of (fx, fy)

    T. This is shown on the right of the figure.

    5 Differential Equations

    The prototype: One of the simplest of differential equations isdx

    dt= ax

    where a is a scalar and x is a real valued function of t. The idea is that the differentialequality x = ax implicitly specifies the function x(t) (here x denotes dx/dt). In thisparticular example, it is easy to verify that x(t) = ceat is a solution. To fix the constantc in the solution we need to know the value of x at some time t. This can be done byspecifying an initial condition: x(0) = c. The solution is far less obvious for more complexdifferential equations. Hence assuming that a solutions exists, one would like to solve forit using numerical methods.

    Vector differential equations: For example, the problem of finding a solution becomesharder if we consider coupled linear equations such as:

    xy

    =

    a11 a12a21 a22

    x(t)y(t)

    with the initial condition (x(0), y(0)) = (x0, y0). Here the aij are given real numbersand x(t) and y(t) are functions of t that are implicitly defined by the coupled linearrelationship between x(t), y(t) and the derivatives x and y.

    The problem is even harder if the equations on the right hand side are nonlinear.

    Working example: As a working example, consider the Van der Pol equations:xy

    =

    y x3 + x

    x

    For a given initial condition (x0, y0) we seek a pair of functions (x(t), y(t)) that satisfythese differential constraints. The equations on the right hand side can be coded as afunction M-file:

    14

  • 7/27/2019 Tutorial 3 Matlab Sept07

    15/19

    function zdot=vdpol(t,z)

    zdot=[z(2)-z(1)^3+z(1); -z(1)];

    The variable t in the above allows for the possibility that the RHS of the differentialequation could (in general) depend on time t. This format for defining the RHS is assumedby MATLABs o.d.e. solvers.

    2 1.5 1 0.5 0 0.5 1 1.5 22

    1.5

    1

    0.5

    0

    0.5

    1

    1.5

    2

    x

    y

    0 2 4 6 8 10 12 14 16 18 202

    1.5

    1

    0.5

    0

    0.5

    1

    1.5

    2

    t

    x,

    y

    x

    y

    Figure 8: Left: A quiver plot of the vector field of the Van der Pol equation together with asolution of the differential equation. Right: Solutions x(t) and y(t) plotted versus time.

    Vector field: Note that the right hand side of our differential equation specifies a vectorfield on the plane:

    v(x, y) =

    v1(x, y)v2(x, y)

    =

    y x3 + x

    x

    The vector v(x, y) at point (x, y) is in fact the tangent (x, y) to the solution curve(x(t), y(t)) at the point (x, y).

    Computing a solution with ode45: This is not a course on differential equations. Sowe will not delve in the details of how one goes about computing a solution. Instead wewill simply point out that MATLAB has a variety of built in commands for numerically

    computing an approximate solution. We restrict attention here to the function ode45. Tocall this function we need to specify three things: the RHS of the o.d.e. as a function (seeabove), the time interval over which we seek a solution, and the initial condition (x0, y0).Here is an example:

    Tmin=0; Tmax=20;

    T=[Tmin Tmax];

    z0=[-2;1];

    15

  • 7/27/2019 Tutorial 3 Matlab Sept07

    16/19

    [t z] = ode45(@vdpol,T,z0);

    figure(1)

    plot(z0(1),z0(2),.r)

    hold on

    plot(0,0,.g)plot(z(:,1),z(:,2),-b,LineWidth,2);

    hold off

    xlabel(x);

    ylabel(y);

    It should be clear at this point how you can add a quiver plot of the vector field. A plot thatresults from this addition is shown on the right in Figure 8. The plot on the left shows x(t)and y(t) as functions of time.

    6 Random Walks & SimulationWe already looked at a deterministic dynamical system, the logistic map, which can, under theright conditions, lead to chaotic trajectories. In many applications, it is important to modeldirectly the uncertainty about some quantity, and to deal with distributions, likelihoods andsimilar statistical measures. Examples include subatomic particles in Physics and Chemistry,molecular dynamics, and financial variables.

    From the last application, we look at a simple, but widely used stochastic model of stockprices. We shall model the stock price returns as being independent normally distributedrandom variables. If we break up the continuous time period [0, T] into N equally-spacedintervals of width t bounded by

    0 = t0 < t1 < < tN = T,then with Stn denoting the stock price at time tn = nt, our model is

    StnStn

    = t + n+1, (1)

    where Stn = Stn+1 Stn and {n, n = 1, , N} is a sequence of independent normal randomvariables with mean zero and variance t, the shocks to the stock price. This stochasticdifference equation reads as follows: the left side is the return on the stock over the timeinterval from tn to tn+1. It has two components, the expected part t, and the random partn+1. The parameter , called the annualized expected growth rate quantifies the rate at which

    we expect the stock to grow over one year (e.g. = 0.08 means we would expect 8% growthfrom investing in this stock for one year). The uncertainty about how the stock will actuallymove over time is captured by the random variables . They are chosen to be mean zero, andhave variance equal to the length of the time period t. There is a good reason for this randomwalk scaling but we will not get into that here. The parameter , which is called the volatility,measures the degree of uncertainty: a more volatile stock fluctuates more wildly.

    A couple of simulated stock price paths are shown in Figure 9. The effects of differentgrowth rates and different volatilities are shown in Figure 10.

    16

  • 7/27/2019 Tutorial 3 Matlab Sept07

    17/19

    0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5100

    150

    200

    250

    300

    350

    400

    Time

    StockPrice

    S

    mu=0.2, sigma=0.15

    0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5100

    150

    200

    250

    300

    350

    400

    Time

    StockPrice

    S

    mu=0.2, sigma=0.15

    Figure 9: Two simulated stock price paths. The blue curve shows the expected growth.

    0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 550

    100

    150

    200

    250

    300

    350

    400

    Time

    StockPrice

    S

    mu1=0.2, mu1=0.1, sigma=0.15

    mu1mu2

    0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 580

    100

    120

    140

    160

    180

    200

    220

    Time

    StockPrice

    S

    mu=0.2, sigma1=0.15, sigma2=0.3

    sigma1sigma2

    Figure 10: The effect of varying (left) and (right).

    17

  • 7/27/2019 Tutorial 3 Matlab Sept07

    18/19

    To generate these simulation from MATLAB, the following script can be used.

    clear

    T=5; % Simulate up till this time (in years)N=250; % Number of time steps

    dt=T/N;

    mu=0.2; % Growth rate

    sigma=0.15; % Volatility

    t=[0:dt:T];

    epss=randn(1,N); % N independent Normal(0,1) Random numbers

    S=zeros(1,N+1); % Reserve space: not necessary, but recommended.

    S(1)=100; % Initial stock price

    for n=1:N;

    S(n+1) = S(n) * (1 + mu*dt + sigma*sqrt(dt)*epss(n));

    end

    figure(1)

    clf

    plot(t,S,r,t,S(1)*exp(mu*t))

    xlabel(Time)

    ylabel(Stock Price S)title(\mu=0.2, \sigma=0.15)

    The main new command here was randn(M,N) which calls MATLABs random numbergenerator to return an M N matrix of random numbers, each drawn from an independentstandard (mean zero, variance one) normal distribution. To obtain a normal with variance t,we take a standard normal and multiply by

    t.

    7 Exercises

    1. Write a script to mesh plot, contour plot and image plot the function:

    f(x, y) = e((x+1)2+(y+1)2/4) 2e12 ((x2)2+y2)

    Use help contour to see how to control the number of contour lines plotted. Your plotsshould like those shown in Figure 11.

    2. Write a script to quiver plot the vector field of the Van der Pol equation. Superimpose onthis quiver plot two solutions over the time interval [0, 20]. One solution should start very

    18

  • 7/27/2019 Tutorial 3 Matlab Sept07

    19/19

    4

    2

    0

    2

    4

    4

    2

    0

    2

    42

    1.5

    1

    0.5

    0

    0.5

    1

    xy

    f

    x

    y

    4 3 2 1 0 1 2 3 44

    3

    2

    1

    0

    1

    2

    3

    4

    x

    y

    5 10 15 20 25 30 35 40 45 50

    5

    10

    15

    20

    25

    30

    35

    40

    45

    50

    1.5

    1

    0.5

    0

    0.5

    Figure 11: Plots of the function in exercise 1.

    close to the origin, the other should start at the point (2, 0.5). Each solution should beplotted in a different color.

    3. Modify your code from exercise 2 to quiver plot the vector field of the linear equation

    xy

    =

    2 66 2

    x(t)y(t)

    and superimpose on this quiver plot the two solutions starting from (0, 2) and (0, 2).4. Consider the stock price model (1) with the parameter values = 0.08 and = 0.4 and

    initial stock price S0 = 100. Use Monte carlo simulation to estimate the probability thatthe stock price ever drops below 80 over the course of a year. To do this, take T = 1 andsimulate (to start with) 1000 stock price trajectories. Count what fraction of these pathsever cross below 80 this is the estimate of the probability we are looking for. Increase

    the number of paths to 10, 000, then 50, 000 and 100, 000: how does the estimate change?The probability is approximately

    log(1.25)

    2

    10

    1

    s3/2e(log(1.25))

    2/(22s)ds.

    Compute (numerically) the integral if you can !

    19