You are on page 1of 19

SEAS Short Course on MATLAB Tutorial 3: Plots & Other Functions

Peter J. Ramadge & Ronnie Sircar 12 September, 2007

Summary

This tutorial is a set example applications intended to enrich the material from the previous tutorials. 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 gure 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 elds 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 nd the solution of an o.d.e. randn - generate a random number drawn from a normal distribution.

2
2.1

More Complex 2-D Plots


Plotting a trajectory of the logistic map

We will explore additional aspects of 2-D curve plotting by investigating the famous logistic map: xk = a(1 xk1 )xk1 . It arises in the study of population dynamics where it provided one of the rst simple examples of chaotic behavior from a deterministic equation, as we shall see. Dening the function f (x) = a(1 x)x, we generate a sequence of scalar values by the iteration xk = f (xk1 ), k = 0, 1, 2, . . . . The rst value, x0 , is called the initial condition and the entire sequence is called the trajectory starting from x0 . The value a is a xed but selectable parameter. We assume that 0 a 4 and that x0 [0, 1]. In this case, f maps the unit interval 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-le taking two parameters and returning 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 that a 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 gure window n the active gure window. 2

0.9

0.9

0.8

0.8

0.7

0.7

0.6

0.6

xk

0.5

xk a = 2.5 x = 0.7
0

0.5

0.4

0.4

0.3

0.3

a = 3.25 x = 0.7
0

0.2

0.2

0.1

0.1

10

15

20

25 30 iteration number k

35

40

45

50

10

15

20

25 30 iteration number k

35

40

45

50

0.9

0.9

0.8

0.8

0.7

0.7

0.6

0.6

xk

0.5

xk a = 3.5 x0 = 0.7

0.5

0.4

0.4

0.3

0.3

a = 3.8 x0 = 0.7

0.2

0.2

0.1

0.1

10

15

20

25 30 iteration number k

35

40

45

50

10

20

30

40

50 60 iteration number k

70

80

90

100

Figure 1: Trajectories of the logistic equation. The command clf clears the current gure window. Before you begin a new plot, it is a good practice to clear the window. The LineWidth parameter controls the thickness of the line used in plotting. It can be set within the plot command as indicated. The axis command controls many aspects of the plot axis. Here we have used it to manually set the upper and lower limits of the x and y axes. The syntax for this is axis([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

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 left trajectory, a = 2.5 and the trajectory settles into the nal 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 is called a periodic orbit with period 2. As a increases still further the character of the trajectory changes again. For a = 3.5, the trajectory from x0 = 0.7 now settles into a periodic orbit with period 4. Finally, for a = 3.8 the trajectory appears chaotic in that it does not settle into any discernable repeating pattern. You can try dierent values of a and x0 yourself and examine the resulting trajectories.

2.2

Multiple curves on a single plot

The xed points of the logistic equation are the solutions of the equation f (x) = x. These occur at intersections of the curve y = f (x) with the line y = x. For a > 1, the only solutions are 0 and x = a 1/a. Periodic orbits can be found in a similar fashion. For a period 2 orbit, f (x1 ) = x2 and f (x2 ) = x1 . Thus f (f (x1 )) = x1 and f (f (x2 )) = x2 , i.e., x1 and x2 are xed points of the composition f2 () = f (f ()). Notice that the xed points of f are always xed points of f2 . So period 2 orbits are the xed points of f2 that are not xed points of f1 = f .
1 a = [3.5] 0.9 0.9 1 a = [2.8 3 3.2 3.4]

0.8

0.8

0.7

0.7

0.6 fk(x) fk(x) y=x f1 f 0 0 0.1 0.2 0.3 0.4 0.5 x


2

0.6

0.5

0.5

0.4

0.4

0.3

0.3

0.2

0.2 y=x f1 f 0.6 0.7 0.8 0.9 1 0 0 0.1 0.2 0.3 0.4 0.5 x
2

0.1

0.1

0.6

0.7

0.8

0.9

Figure 2: The logistic equation f and its composition f2 . The xed points of f 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 on the same graph. Here is a MATLAB function that will do the job: function y=plotf(a,N,fig) 4

% 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) grid; axis([0 1 0 1]); xlabel(x) ylabel(f_k(x)); text(0.15,0.95,sprintf(a = %4.2f,a)) axis(square);

% plot the line y=x in black dashes

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 end hold 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 rst erasing what is already there. The command hold off turns o this feature. linspace sets up a row vector of equally spaced points between given upper and lower limits. The syntax is linspace(xmin,xmax,N) where xmin and xmax are the limits and N is the number of points. We have used the axis command three times: to set the upper and lower limits on the x and y axes, to make the scales on the two axes equal, and to force the aspect ratio of the 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 dened. 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

function of the loop variable k. We have constructed a text string as the concatenation of the string returned by myc(k) and the string -. To do this we simply make the strings the 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 only intersects the line x = y at the xed point x . However, for a > 3 there are three intersections of f2 with the line: one at x , one above x and one below x . The points above and below x are not xed points of f but they are xed points of f2 . Hence they form a nontrivial periodic orbit of period 2.
1 a = [3.55]

0.8

0.6 fk(x) 0.4 0.2 0 0

0.1

0.2

0.3

0.4

0.5 x

0.6

0.7

0.8

0.9

y=x

f1

f2

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 hence to determine visually if there are period 3, 4, etc., orbits. The plot in Figure 3 shows the result for periods 1 through 5 with a = 3.55. How many periodic orbits does the graph indicate and what are the periods? Notice the aspect ratio of the plot. We replaced the command axis(square) with the command pbaspect([2.5 1 1]). This changes the aspect ratio of the 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 can modify the inner loop as follows: for k=1:kmax y=logistic(y,a(j)); plot(x,y,[c(k) -],LineWidth,lw); pause end 6

The command pause, without any argument, causes MATLAB to wait for the user to press any key. Another useful tool is subplot. The command subplot(M,N,k) tells MATLAB that we want to plot several plots on the same gure 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 indexed by a single integer k by counting along the rows from top to bottom. So if M=2 and N=3, then k=3 is the third subplot on the rst row, k=5 is the second subplot on the second row, and so on. 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-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 might be the displacement of a vibrating plate at location (x, y ), or the intensity of an analog image 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-D Gaussian density functions: f (x, y ) = e 2 (x
1 2 +y 2 )

+ e 2 ((x2)

2 +(y 2)2 )

Representing a 2-D function in MATLAB: To represent a 2-D function in MATLAB we must restrict the range of values of x and y to nite intervals and sample the values of the function over this range at a nite number of points. Assume we restrict attention to the rectangle: xmin x xmax and ymin y ymax . A simple way to sample x and y is to x 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 dene 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, we need to represent the sample values of x and y as matrices. We do this by replicating the row vector x M times (one for each value in y) to form a matrix X. Each column of X has the same value in each entry - for column j this is the value xj . We do the same thing to form a matrix Y except that each column of Y is a replicate of the column vector y. A simple example: 7

>> >> >> >> >> X =

x=0:1:2; y=0:1:3; X=[x;x;x;x]; Y=[y,y,y]; X

0 0 0 0 >> Y Y = 0 1 2 3

1 1 1 1

2 2 2 2

0 1 2 3

0 1 2 3

Note that X and Y are the same size with M rows, the number of samples in y, and N columns, the number of samples in x. To compute the 2-D function f at the sample locations you simply use X and Y in place of x and y in the formula for f . For example, the function in our working example f (x, y ) = e 2 (x
1 2 +y 2 )

+ e 2 ((x2)

2 +(y 2)2 )

is computed at the sample points as follows: F0=exp(-0.5*(X.^2+Y.^2)); F1=exp(-0.5*((X-2).^2+(Y-2).^2)); F=F0+F1 F = 1.0183 0.6886 0.2707 0.0932 0.6886 0.7358 0.6886 0.3746 0.2707 0.6886 1.0183 0.6080

As expected, the result is a matrix of size M N since there are M N sample points (xj , yk ) arranged in a rectangular grid. 8

meshgrid: To form X and Y as outlined above when N and M are large is tedious. Hence MATLAB provides a command to do the job: [X Y]=meshgrid(x,y); mesh and contour: After computing the values of f on a 2-D sample grid, there are several ways we can plot them. The command mesh(X,Y,F) will produce a 3-D mesh plot of the computed values plotted versus x and y. The command contour(X,Y,F) will produce a contour plot versus x and y. The mesh and contour plots shown in Figure 4 are produced by the following script: clear all xmax=4; xmin=-xmax; ymax=4; ymin=-ymax; N=50; M=N; x=linspace(xmin,xmax,N); y=linspace(ymin,ymax,M); [X Y]=meshgrid(x,y); G=@(A,B) exp(-0.5*A.^2 -0.5*B.^2); F0=G(X,Y); F1=G(X-2,Y-2); F=F0+F1; figure(1) clf mesh(X,Y,F) xlabel(x) ylabel(y) zlabel(f); figure(2) clf contour(X,Y,F) xlabel(x) ylabel(y) zlabel(f) grid

% anonymous function

Note that we computed the function f by rst dening the 2-D Gaussian as an anonymous function: G=@(A,B) exp(-0.5*A.^2 - 0.5*B.^2); Here A and B are the arguments to be passed to the function and exp(-0.5*A.^2 -0.5*B.^2) is the expression dening the function. Then we called this function twice to compute F.

1.4 1.2 1
1 2

0.8 f 0.6 0.4


1 0 y

0.2 0 4 2 0 0 2 y 4 4 2 x
4 3 2 1 0 x 1 2 3 4 2

4 2
3

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 computer screen to fully appreciate the images in this section. Displaying a matrix as an image: A matrix A is a rectangular array of numbers. This array 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 rst column of the color map represents a fraction of red, the second of green and the third of blue. So (1, 0, 0) represents pure red; (1, 1, 1) is white; (0, 0, 0) is black; and (0.5, 0.5, 0.5) is mid gray. The number of rows in the color map is the number of colors used to represent numerical values. The idea is that each number in the interval [0, 1] is mapped in an order preserving way to a row of the color map and the color coded by that row is used to represent the number in an image. MATLAB has several predened color maps each with 256 rows. Some of them are displayed as images in Figure 5. The rst row (top of the gure) represents the number 1 and the last row represents 0. The default color map is 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

50

50

50

50

50

100

100

100

100

100

150

150

150

150

150

200

200

200

200

200

250 0.5 1 jet 1.5

250 0.5 1 hot 1.5

250 0.5 1 cool 1.5

250 0.5 1 copper 1.5

250 0.5 1 gray 1.5

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 same except displayed with the copper color map.
1 5 5 1

0.9

0.9

10

0.8

10

0.8

15

0.7

15

0.7

20

0.6 y

20

0.6

25

0.5

25

0.5

30

0.4

30

0.4

35

0.3

35

0.3

40

0.2

40

0.2

45

0.1

45

0.1

50 5 10 15 20 25 x 30 35 40 45 50

50 5 10 15 20 25 x 30 35 40 45 50

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

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 a number 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 Princeton and S(1,4:end) returns Tigers. However, if the strings have dierent lengths, they cannot be stored directly in a matrix without rst padding the shorter strings with spaces so that all strings have the same length. This can be done with the char command. However, a simpler way is to use a cell array of strings. The command cmaps={jet hot cool copper gray} denes a cell array of strings. The delimiters { and } enclose the strings included in the array. The elements of the cell array can be referenced using braces { }: cmaps{1} is the string jet, cmaps{3} is the string cool, and so on. The function eval evaluates a string as if it were an MATLAB expression. In our case, the string is the k th 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 the color map map. If X is an p q 3 array of real numbers in the the range [0, 1], the command image interprets the matrix X(:,:,k) as the R (k = 1), G (k = 2) and B (k = 3) values of an image and display the image on the screen. This is probably more than you needed to know at this point. Dont worry if this seems a little complicated. Its an advanced example.

12

y 3 2 1 0 x 1 2 3 4

4 4

4 4

0 x

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

Vector Fields and Quiver Plots


Gradient: Let fx = f /x and fy = f /y denote the partial derivatives of the function f (x, y ) with respect to x and y . The gradient of f (x, y ) is the vector of partial derivatives f (x, y ) f (x, y ) = x fy (x, y ) At each point (x, y ), the gradient vector points in the direction of steepest increase of the function f at that point and its magnitude is a measure of how rapidly the function is changing in that direction. The negative of the gradient points in the direction of steepest decrease of the function. Hence a simple method for nding a (local) minimum of a function is to take small steps in the direction of the negative gradient, a method appropriately known as steepest descent. The gradient is an example of a 2-D vector eld: a function that associates with each point (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 eld with a MATLAB quiver plot. The vector eld 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 previous section. Then we can display the vector eld on a quiver plot with the command quiver(X,Y,V1,V2). This plots v (x, y ) as a small arrow from the point (x, y ) pointing in 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 ) = xe 2 (x +y ) (x 2)e 2 ((x2) +(y2) ) 1 1 2 2 2 2 ye 2 (x +y ) (y 2)e 2 ((x2) +(y2) ) 13
1 2 2 1 2 2

We can display this as a quiver plot by adding the following additional commands to our previous 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 dened and computed in the script to plot f . The result is shown on the left in Figure 7. By using hold on and hold off we can combine a contour plot of f with the quiver plot of (fx , fy )T . This is shown on the right of the gure.

Dierential Equations
The prototype: One of the simplest of dierential equations is dx = ax dt where a is a scalar and x is a real valued function of t. The idea is that the dierential equality x = ax implicitly species the function x(t) (here x denotes dx/dt). In this at particular example, it is easy to verify that x(t) = ce is a solution. To x the constant c in the solution we need to know the value of x at some time t. This can be done by specifying an initial condition: x(0) = c. The solution is far less obvious for more complex dierential equations. Hence assuming that a solutions exists, one would like to solve for it using numerical methods. Vector dierential equations: For example, the problem of nding a solution becomes harder if we consider coupled linear equations such as: x y = a11 a12 a21 a22 x(t) y (t)

with the initial condition (x(0), y (0)) = (x0 , y0 ). Here the aij are given real numbers and x(t) and y (t) are functions of t that are implicitly dened by the coupled linear relationship 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: x y = y x3 + x x

For a given initial condition (x0 , y0 ) we seek a pair of functions (x(t), y (t)) that satisfy these dierential constraints. The equations on the right hand side can be coded as a function M-le: 14

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 dierential equation could (in general) depend on time t. This format for dening the RHS is assumed by MATLABs o.d.e. solvers.
2 2 x y 1.5 1.5

0.5

0.5

x,y 1.5 1 0.5 0 x 0.5 1 1.5 2

0.5

0.5

1.5

1.5

2 2

10 t

12

14

16

18

20

Figure 8: Left: A quiver plot of the vector eld of the Van der Pol equation together with a solution of the dierential equation. Right: Solutions x(t) and y (t) plotted versus time. Vector eld: Note that the right hand side of our dierential equation species a vector eld on the plane: v (x, y ) y x3 + x v (x, y ) = 1 = v2 (x, y ) 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 dierential equations. So we will not delve in the details of how one goes about computing a solution. Instead we will 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. To call this function we need to specify three things: the RHS of the o.d.e. as a function (see above), 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

[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 eld. A plot that results 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.

Random Walks & Simulation

We already looked at a deterministic dynamical system, the logistic map, which can, under the right conditions, lead to chaotic trajectories. In many applications, it is important to model directly the uncertainty about some quantity, and to deal with distributions, likelihoods and similar statistical measures. Examples include subatomic particles in Physics and Chemistry, molecular dynamics, and nancial variables. From the last application, we look at a simple, but widely used stochastic model of stock prices. We shall model the stock price returns as being independent normally distributed random variables. If we break up the continuous time period [0, T ] into N equally-spaced intervals of width t bounded by 0 = t0 < t1 < < tN = T, then with Stn denoting the stock price at time tn = nt, our model is Stn = t + n+1 , S tn

(1)

where Stn = Stn+1 Stn and {n , n = 1, , N } is a sequence of independent normal random variables with mean zero and variance t, the shocks to the stock price. This stochastic dierence equation reads as follows: the left side is the return on the stock over the time interval from tn to tn+1 . It has two components, the expected part t, and the random part n+1 . The parameter , called the annualized expected growth rate quanties the rate at which we expect the stock to grow over one year (e.g. = 0.08 means we would expect 8% growth from investing in this stock for one year). The uncertainty about how the stock will actually move over time is captured by the random variables . They are chosen to be mean zero, and have variance equal to the length of the time period t. There is a good reason for this random walk 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 uctuates more wildly. A couple of simulated stock price paths are shown in Figure 9. The eects of dierent growth rates and dierent volatilities are shown in Figure 10. 16

mu=0.2, sigma=0.15 400 400

mu=0.2, sigma=0.15

350

350

300 Stock Price S Stock Price S 0 0.5 1 1.5 2 2.5 Time 3 3.5 4 4.5 5

300

250

250

200

200

150

150

100

100

0.5

1.5

2.5 Time

3.5

4.5

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

mu1=0.2, mu1=0.1, sigma=0.15 400 mu1 mu2 350 200 220 sigma1 sigma2

mu=0.2, sigma1=0.15, sigma2=0.3

300

180

Stock Price S

250

Stock Price S 0 0.5 1 1.5 2 2.5 Time 3 3.5 4 4.5 5

160

200

140

150

120

100

100

50

80

0.5

1.5

2.5 Time

3.5

4.5

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

17

To generate these simulation from MATLAB, the following script can be used. clear T=5; N=250; dt=T/N;

% Simulate up till this time (in years) % Number of time steps

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 number generator to return an M N matrix of random numbers, each drawn from an independent standard (mean zero, variance one) normal distribution. To obtain a normal with variance t, we take a standard normal and multiply by t.

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)

2e 2 ((x2)

2 +y 2 )

Use help contour to see how to control the number of contour lines plotted. Your plots should like those shown in Figure 11. 2. Write a script to quiver plot the vector eld of the Van der Pol equation. Superimpose on this quiver plot two solutions over the time interval [0, 20]. One solution should start very 18

5
3

0.5 10

1 0.5 0 0.5
0 2

15 0
1

20

1
30

1.5 2 4 2 0 0 2 y 4 4 2 x 2 4

25

0.5

35
2

40 1.5
3

45

4 4

50
3 2 1 0 x 1 2 3 4

10

15

20

25 x

30

35

40

45

50

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 be plotted in a dierent color. 3. Modify your code from exercise 2 to quiver plot the vector eld of the linear equation x y = 2 6 6 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 that the stock price ever drops below 80 over the course of a year. To do this, take T = 1 and simulate (to start with) 1000 stock price trajectories. Count what fraction of these paths ever 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
1 0

1 s3/2

e(log(1.25))

2 /(2 2 s)

ds.

Compute (numerically) the integral if you can !

19

You might also like