next up previous
Next: About this document ... Up: tutorial3 Previous: Another case: the method

Cobweb plots


The last exercise is to produce a cobweb plot like that on page 9 of the notes. To test this we will return to the problem \bgroup\color{red}$x=\cos x$\egroup. Create a new file called iteration2.m using the cp command (or the editor):

cp iteration.m iteration2.m

\bgroup\color{red}\framebox{\em ADD CODE TO FILE}\egroup \bgroup\color{black}$\phantom{0}$\egroupChange the plotting commands in iteration2.m so that both \bgroup\color{black}$y=x$\egroup and \bgroup\color{black}$y=g(x)=\cos x$\egroup are displayed. Run iteration2.m, using an interval of \bgroup\color{black}$x \in [-4,4]$\egroup to ensure that this part is right.

\bgroup\color{red}\framebox{\em ADD CODE TO FILE}\egroup \bgroup\color{black}$\phantom{0}$\egroupTo give a better visual test of the cobweb plot, start with \bgroup\color{black}$x_0=-2$\egroup. We now need to interpret the hand algorithm in MATLAB. The first iterate \bgroup\color{black}$x_1$\egroup is \bgroup\color{black}$\cos(-2)$\egroup; to locate this point graphically move horizontally across the plot until the line \bgroup\color{black}$y=x$\egroup is encountered. Thus our starting point for the first vertical line is (x(1),x(1)). The end point of the line has the corresponding \bgroup\color{black}$y$\egroup-value cos(x(1)) or g(x(1)) i.e. x(2). Thus our first (vertical) line runs from (x(1),x(1)) to (x(1),x(2)). The first (horizontal) line then runs from (x(1),x(2)) to (x(2),x(2)). So we need code like

plot( [x(n) x(n)], [x(n) x(n+1)], 'k') % vertical line

plot( [x(n) x(n+1)], [x(n+1) x(n+1)], 'k--') % dashed horizontal line

pause % requires user to hit enter to continue to the next iteration

Your code will also require a clf command right at the beginning, to clear the figure at the start of each run, and a hold on command after the first plot command, to ensure that all plots are on the figure at one time.

Additional: Write a short MATLAB function that will put a small arrow head at the end of each of the vertical and horizontal lines, as in the figure. You will need to pass the angle each line makes to the horizontal to this function; the MATLAB function atan2 may be useful here.

Figure: Cobweb plot for fixed-point iteration solution of $x=\cos x$.
\includegraphics[width=7cm,height=7cm]{cobweb.ps}


next up previous
Next: About this document ... Up: tutorial3 Previous: Another case: the method
Charlie Macaskill 2004-07-26